476 CHAPTER 12 Drawing with HTML5
The examples that follow have a simple webpage with a <canvas> element and references
to canvasPath.css, canvasPath.js, and jquery-1.8.2.js files as follows.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="Content/canvasPath.css" rel="stylesheet" />
<script src="Scripts/jquery-1.8.2.js"></script>
<script src="Scripts/canvasPath.js"></script>
</head>
<body>
<canvas id="myCanvas" width="800" height="600">
You need a browser that supports HTML5!
</canvas>
</body>
</html>
The canvasPath.js file is presented in each example. The canvasPath.css file contains the
following style rule.
canvas {
border: 1px solid black;
}
Drawing lines
The easiest path to create is one composed of lines. This is accomplished by using the lineTo
method, which accepts x and y parameters. The following is an example of using lines to cre-
ate shapes that have a yellow outline and green fill.
$(document).ready(function () {
drawLine();
});
function drawLine(){
var canvas = document.getElementById('myCanvas')
, ctx = canvas.getContext('2d');
ctx.fillStyle = 'green';
ctx.strokeStyle = 'yellow';
ctx.lineWidth = 10;
ctx.beginPath();
ctx.moveTo(100, 250);
ctx.lineTo(150, 350);
ctx.lineTo( 50, 350);
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.moveTo(150, 250);
ctx.lineTo(250, 250);
ctx.lineTo(200, 350);