Canvas How to - Draw gradient ellipse








Question

We would like to know how to draw gradient ellipse.

Answer


<!--from w  ww.  j ava 2 s  .  com-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var canvas = document.getElementById('test')
    var ctx = canvas.getContext('2d');
    ctx.save();
    ctx.beginPath();
    var gradient = ctx.createRadialGradient(250, 250, 0, 250, 250, 100);  
    gradient.addColorStop(0, "rgba(125, 0, 0, 255)");  
    gradient.addColorStop(1, "rgba(125, 255, 125, 255)");  
    ctx.fillStyle = gradient;
    ctx.arc(250, 250, 100, 0, 2 * Math.PI, false);
    ctx.transform(1,0,0,0.5,0,125);
    ctx.fill();
    ctx.restore();  
    ctx.beginPath();
    ctx.rect(0, 0, 100, 100);
    ctx.fillStyle = 'yellow';
    ctx.fill();
}//]]>  
</script>
</head>
<body>
  <canvas id="test" width="500" height="500">
</body>
</html>

The code above is rendered as follows: