Practice Set, Week 4, Drawing Lines on the Canvas
by Carlos Ng
HTML
<b>Practice Set 14.1: Draw an X</b>
<p>In this practice problem, you will use CanvasRenderingContext2D methods to draw lines between opposite corners to make an X. See the Javascript comments for guidance.</p>
<div>Canvas
<br/>
<canvas id="c1" width="300" height="200"></canvas>
</div>
CSS
canvas {
border:1px solid blue;
}
#output {
border: 1px solid gray;
}
div {
float:left;
}
p {
clear: both;
}
JavaScript
// get the canvas and context objects
var canvas = document.getElementById("c1");
var ctx = canvas.getContext('2d');
// We can draw on this 'ctx' object. Let's set some styles
ctx.strokeStyle = "red";
ctx.lineWidth = "2";
for (var i = 0; i <= ctx.canvas.width; i += 300)
{
ctx.beginPath(); // initialize a new drawing path
ctx.moveTo(i,0); // move the pen to where we'll start
ctx.lineTo(300-i, 200); // create a line with the pen
ctx.stroke();
};