HTML and CSS Reference
In-Depth Information
context.beginPath();
context.moveTo(0, 0);
context.lineTo(100, 100);
context.stroke();
On the canvas, there's now a line drawn from the top-left corner (0, 0), to 100, 100. After you draw a line,
the ending point for that line is the starting point for the next one. Or, you can use the method
context.moveTo to specify a new starting point for the next line.
Think of the drawing API as a robot holding a pen on a piece of paper. First, you move the pen to the start
position at 0, 0. When you tell the robot to draw a line to a point, it moves the pen across the paper to that
new position. For each new line, it moves from wherever it left off, to the next new point. context.moveTo
is like saying, “Okay, now lift up the pen and move it to this next point.” Although it does not result in any
new graphic content, it will affect how the next command is carried out. You generally call
context.moveTo as your first graphics command to place the drawing API “pen” where you want to begin.
You now have enough drawing commands to do something interesting. Let's create a simple drawing
program that will rely on the canvas drawing API for its content. Here's the example:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Drawing App</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
mouse = utils.captureMouse(canvas);
function onMouseMove () {
context.lineTo(mouse.x, mouse.y);
context.stroke();
}
canvas.addEventListener('mousedown', function () {
context.beginPath();
context.moveTo(mouse.x, mouse.y);
canvas.addEventListener('mousemove', onMouseMove, false);
}, false);
canvas.addEventListener('mouseup', function () {
canvas.removeEventListener('mousemove', onMouseMove, false);
}, false);
};
</script>
</body>
</html>
Search WWH ::




Custom Search