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.
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();
}
| Attachment | Size |
|---|---|
| drawText.htm | 5.44 KB |

