HTML 5 canvas - adding text

Canvas element - adding text

A previous example used the following three diagrams as part of a maths refresher. The original diagrams were (of course!) drawn using the canvas element. By placing the mouse over any canvas element on any HTML page, and right clicking on it, you can then save the resulting drawing just as you would for any other image.

angles radians canvas cordinates

The code for the first two examples is shown below. based on these, its left as an exercise for you to draw the last diagram. The third function I called DrawGrid(). The only new command you need in order to draw the filled rectangle is shown below.

   context.fillRect(75,75,125,125);  //set up filled rectangle

The diagrams were originally drawn slightly bigger, then scaled to fit the page with the following lines of code. Before performing any transformation, such as scaling, you should first save the current context to stack, so it can be subsequently restored.

  var sx = 0.9; var sy = 0.9;        //set scale values
  context.scale(sx,sy); 
function Triangle() 
{ 
  // Create a right angle triangle
  var canvas = document.getElementById("fig1");  
  var context = canvas.getContext("2d");
    
  var x = 200; var y = 150;               //lengths of adjacent and opposite sides
  var originx = 50; var originy = 200;    //set origin

  context.beginPath();                    //start new path
  context.moveTo(originx,originy);
  context.lineTo(originx + x,originy);
  context.lineTo(originx + x,originy - y);
  context.closePath();
  context.stroke();
  
  context.font = "italic 12pt serif";
  context.strokeText("A",originx-20,originy);
  context.strokeText("B",originx+x+10,originy);
  context.strokeText("C",originx+x+10,originy-y);
  context.strokeText("a",originx+25,originy-5);
  context.strokeText("BC = AC*sin(a)",20,originy-y); 
  context.strokeText("AB = AC*cos(a)",20,originy-y+25); 
  context.closePath();
}  

function Radian()
{
  var canvas = document.getElementById("fig1");  
  var context = canvas.getContext("2d");
  
  var radius = 200;
  var x = radius*Math.cos(1); var y =radius*Math.sin(1); 
  context.save();
  context.translate(50,200);
  
  context.beginPath();       //start new path
  context.moveTo(0,0);       //draw first line of length radius
  context.lineTo(radius,0);
  context.moveTo(0,0);		 //draw second line of length radius
  context.lineTo(x,-y);
  context.closePath();
 
  //arc(originx,originy,radius,startAngle,endAngle, anticlockwise)
  // anticlockwise is either true or false
  context.arc(0,0,radius,0,-1,true);     //draw arc of 1 radian
  context.stroke();
  
  context.font = "italic 12pt serif"; 
  context.strokeText("a = 1 radian",15,-10); 
  context.strokeText("2*PI radians = 360 degrees",-25,-175); 
  context.strokeText("radius",180,-120); 
  context.restore();
}
AttachmentSize
drawText.htm5.44 KB