HTML and CSS Reference
In-Depth Information
<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),
x0 = 100,
y0 = 200,
x2 = 300,
y2 = 200;
canvas.addEventListener('mousemove', function () {
context.clearRect(0, 0, canvas.width, canvas.height);
var x1 = mouse.x,
y1 = mouse.y;
//curve toward mouse
context.beginPath();
context.moveTo(x0, y0);
context.quadraticCurveTo(x1, y1, x2, y2);
context.stroke();
}, false);
};
</script>
</body>
</html>
Load this file in your browser and move the mouse around. The script has two preset points for the
beginning and ending points, and uses the mouse position for the control point. Notice that the curve never
reaches the control point, but gets about halfway there.
Curving through the control point
If you want the curve to hit a point, the following formula calculates a control point, so the curve goes
through the point you specify. Again, you start with x0, y0 and x2, y2 as the end points, and x1, y1 as
the control point. We call the point you want to curve through xt, yt (t for target). In other words, if you
want the curve to be drawn through xt, yt , what x1, y1 do you need to use? Here's the formula:
x1 = xt * 2 - (x0 + x2) / 2;
y1 = yt * 2 - (y0 + y2) / 2;
Basically, you multiply the target by two, and subtract the average of the starting and ending points. You
can graph the whole formula and see exactly how it works. Or, you can test it, see that it works, and
assume that it always will.
To see it in action, using the mouse coordinates as xt, yt , you need to change only two lines from the
previous example. Change the following lines:
x1 = mouse.x;
y1 = mouse.y;
to the following:
 
Search WWH ::




Custom Search