Course notes 19
syllabus | schedule | exercises | assignments | class notes | resources | students | ARTC courses

Gradients

The command takes 4 attributes: the starting point (x1,y1) and end point (x2,y2) of the gradient.

createLinearGradient(x1,y1,x2,y2);

Usage:

 var linGradient = ctx.createLinearGradient(0,0,150,200);

To specify the colors that occur along the gradient, you need to add color stops:

addColorStop(position, color)

The position needs to be a number between 0 and 1. 0 is the start of the gradient and 1 is the end of the gradient. You can add lots of color stops to a gradient.

Example of a gradient with 4 colors:

      var canvas = document.getElementById('ex01');
      var ctx = canvas.getContext('2d');
	
      var linGradient = ctx.createLinearGradient(0,0,0,150);
      linGradient.addColorStop(0, '#FF0000');
      linGradient.addColorStop(.3, '#FFFF00');
      linGradient.addColorStop(.7, '#00FF00');
      linGradient.addColorStop(1, '#000000');
	  
      ctx.fillStyle = linGradient;
      ctx.strokeStyle = linGradient;
      ctx.fillRect(20,20,120,260);
      ctx.strokeRect(160,20,120,260);

Radial Gradient

The command takes 6 attributes: The first three arguments define an inner circle with coordinates (x1,y1) and radius r1 and an outer circle with coordinates (x2,y2) and radius r2.

createRadialGradient(x1,y1,r1,x2,y2,r2) 

Usage:

 var radialgradient = ctx.createRadialGradient(100,100,0,50,50,100);

Example of two radial gradients:

      var canvas = document.getElementById('ex02');
      var ctx = canvas.getContext('2d');
	  
      var radGradient = ctx.createRadialGradient(110,100,10,100,100,60);
      radGradient.addColorStop(0, '#FF7700');
      radGradient.addColorStop(0.3, 'FFFF00');
      radGradient.addColorStop(0.9, '#773300');  
      radGradient.addColorStop(1, '000000');
      ctx.fillStyle = radGradient;
      ctx.fillRect(0,0,300,300);
      
      var radGradient2 = ctx.createRadialGradient(225,200,1,200,200,40);
      radGradient2.addColorStop(0, '#00FF00');
      radGradient2.addColorStop(0.3, 'FFFF00');
      radGradient2.addColorStop(0.9, '#0000FF');  
      radGradient2.addColorStop(1, 'FFFFFF');
      ctx.fillStyle = radGradient2;
      ctx.fillRect(150,150,150,150);


Text and Shadows

Shadows are supported by Firefox 3.5 or above - other browsers may not support it.

Shadows take 4 parameters:

shadowOffsetX = float - how far away from the text in the X direction
shadowOffsetY = float - how far away from the text in the Y direction
shadowBlur = float - size of the blur
shadowColor = color

fillText takes three parameter: theText, theStartX, theStartY

      ctx.shadowOffsetX = 3;
      ctx.shadowOffsetY = 2;
      ctx.shadowBlur = 4;
      ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
      ctx.font = "28px Arial";
      ctx.fillStyle = "Black";
      ctx.fillText("This will render out text with a shadow.", 20, 32);
}