
previous

page 2
next
And here's how to draw a line on the canvas.
<style>
#c {
border:1px solid red;
}
</style>
<canvas id='c'></canvas>
<script>
var canvas=document.getElementById('c');
var ctx=canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(300,150);
ctx.stroke();
</script>
#c {
border:1px solid red;
}
</style>
<canvas id='c'></canvas>
<script>
var canvas=document.getElementById('c');
var ctx=canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(300,150);
ctx.stroke();
</script>
The first thing we always have to do is to establish a context. We'll only use the 2d context in this tute.
From then on all commands must be prefixed with that context (ctx in my example).
The moveTo and lineTo commands should be fairly obvious BUT for the line to be drawn on the screen, the stroke command is always required.
The beginPath command can be omitted but it seemed that the line width varied when I left it out.
You should be able to work out from this example that the default canvas is 300px wide and 150px high and that the origin is at the top left corner. This means that the y values go down the screen instead of up.
previous
next