Canvas How to - Create Circle gradient








Question

We would like to know how to create Circle gradient.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--from  w  w  w.j a  v a 2  s  .  c  om-->
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var x = 100,y = 75,innerRadius = 5,outerRadius = 70,radius = 60;
    var gradient = ctx.createRadialGradient(x, y, innerRadius, x, y, outerRadius);
    gradient.addColorStop(0, 'white');
    gradient.addColorStop(1, 'blue');
    ctx.arc(x, y, radius, 0, 2 * Math.PI);
    ctx.fillStyle = gradient;
    ctx.fill();
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas"></canvas>
</body>
</html>

The code above is rendered as follows: