Canvas How to - Draw ellipse








Question

We would like to know how to draw ellipse.

Answer


<!--from   w ww.j av a2  s .c  om-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var canvas = document.getElementById("canvas")
    var ctx = canvas.getContext("2d")
    function ellipse(color, lineWidth, x, y, stretchX, stretchY, startAngle, endAngle) {
      for (var angle = startAngle; angle < endAngle; angle += Math.PI / 180) {
        ctx.beginPath()
        ctx.moveTo(x, y)
        ctx.lineTo(x + Math.cos(angle) * stretchX, y + Math.sin(angle) * stretchY)
        ctx.lineWidth = lineWidth
        ctx.strokeStyle = color
        ctx.stroke()
        ctx.closePath()
      }
    }
    ellipse("rgb(34, 278, 123)", 5, 60, 60, 40, 60, 0, Math.PI * 2);
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas"></canvas>
</body>
</html>

The code above is rendered as follows: