HTML and CSS Reference
In-Depth Information
segment0.draw(context);
segment1.draw(context);
}());
Finally, reposition
segment0
so it sits on the end of
segment1
, because
segment1
is now rotated to a
different position:
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
var dx = mouse.x - segment0.x,
dy = mouse.y - segment0.y;
segment0.rotation = Math.atan2(dy, dx);
var w = segment0.getPin().x - segment0.x,
h = segment0.getPin().y - segment0.y,
tx = mouse.x - w,
ty = mouse.y - h;
dx = tx - segment1.x;
dy = ty - segment1.y;
segment1.rotation = Math.atan2(dy, dx);
segment0.x = segment1.getPin().x;
segment0.y = segment1.getPin().y;
segment0.draw(context);
segment1.draw(context);
}());
When you test this example, you see that the segments work as a unit to reach for the mouse. Now, let's
clean up the code so you can add more segments to it easily. Move all of the rotation code into its own
function, named
reach
:
function reach (segment, xpos, ypos) {
var dx = xpos - segment.x,
dy = ypos - segment.y;
segment.rotation = Math.atan2(dy, dx);
var w = segment.getPin().x - segment.x,
h = segment.getPin().y - segment.y;
return {
x: xpos - w,
y: ypos - h
};
}