Canvas How to - Draw a ball in gradient color








Question

We would like to know how to draw a ball in gradient color.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script type='text/javascript'>
$(window).load(function(){<!--   w  ww . ja  v  a2 s.c  o  m-->
        var canvas = document.getElementById("canvas");
        var context = canvas.getContext('2d');
        context.arc(canvas.width / 2, canvas.height / 2, canvas.width / 2 - 2, 0, Math.PI * 2, false);
        context.closePath();
        var orangeGradient = context.createLinearGradient(canvas.width / 2, 0, canvas.width / 2, canvas.height);
        orangeGradient.addColorStop(0, '#ffdd00');
        orangeGradient.addColorStop(1, '#cc6600');
        context.fillStyle = orangeGradient;
        context.fill();
});
</script>
</head>
<body>
  <canvas id="canvas" width=400 height=400></canvas>
</body>
</html>

The code above is rendered as follows: