Practice Set, Week 4, Drawing Lines on the Canvas
by jessupjs
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;
cursor: crosshair;
}
#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";
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
// Declare isDrawing
var isDrawing;
// Remember from the example in
// video 14.3 how to draw lines, or check the MDN docs:
// https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineTo
// In steps:
// call beginPath() to start the drawing path
// call moveTo() to position the pen at the starting point at one corner
$(canvas).mousedown(function(e) {
isDrawing = true;
ctx.beginPath();
ctx.moveTo(e.clientX, e.clientY);
console.log('hit1');
});
// call lineTo() to define a line to the opposite corner
// call stroke() to draw it
$(canvas).mousemove(function(e) {
if (isDrawing) {
ctx.lineTo(e.clientX, e.clientY);
ctx.stroke();
console.log('hit2');
}
});
$(canvas).mouseup(function(e) {
isDrawing = false;
console.log('hit3');
});
// Do this twice so that two corner-to-corner lines cross in the middle - it'll
// look like a big red 'x'