Canvas How to - Create Radial Gradient








Question

We would like to know how to create Radial Gradient.

Answer


<!--from w  w w.ja va  2  s.  c  o  m-->

<!DOCTYPE html>
<html>
<head>
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.5.2.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
    var ctx = $('canvas').get(0).getContext('2d');
    function circle(x, y, r, c) {
        ctx.beginPath();
        var rad = ctx.createRadialGradient(x, y, 1, x, y, r);
        rad.addColorStop(0, c);
        rad.addColorStop(1, 'transparent');
        ctx.fillStyle = rad;
        ctx.arc(x, y, r, 0, Math.PI*2, false);
        ctx.fill();
    }
    ctx.fillRect(0, 0, 256, 256);
    circle(128, 128, 200, 'red');
    circle(64, 64, 30,    'green');
});//]]>  
</script>
</head>
<body>
  <canvas width=256 height=256></canvas>
</body>
</html>

The code above is rendered as follows: