Another effect you can use with canvas shapes is a gradient.
Gradient fills in the canvas can be created either through a linear (createLinearGradient) or radial (createRadialGradient) gradient.
To add colors to the gradient, use the addColorStop property.
<!DOCTYPE html> <html lang='en'> <head> <meta charset='utf-8'> <title>Codecrawl.com: Styling a square</title> <style> canvas { border: 1px solid #000; } </style> </head> <body> <canvas id='canvas' width='400' height='400'></canvas> <script> var canvas = document.getElementById('canvas').getContext('2d'); var grd = canvas.createLinearGradient(0, 200, 200, 0); grd.addColorStop(0, '#000'); // light blue grd.addColorStop(.5, '#ccc'); // dark blue grd.addColorStop(1, '#000'); canvas.fillStyle = grd; canvas.strokeStyle = '#09c'; canvas.lineWidth = 5; canvas.fillRect(0, 0, 200, 200); canvas.closePath(); var grd = canvas.createRadialGradient(300, 250, 2, 200, 200, 250); grd.addColorStop(0, '#000'); grd.addColorStop(1, '#ccc'); canvas.fillStyle = grd; canvas.fillRect(200, 200, 200, 200); canvas.closePath(); </script> </body> </html>
Both gradient methods employ different parameters to control the behavior of the gradient, as shown here:
createLinearGradient(startX, startY, endX, endY) createRadialGradient(startX, startY, startRadius, endX, endY, endRadius)
The radial gradient method can get a little complicated, so it is worth playing around with this; try adding various addColorStop to see what happens.