HTML and CSS Reference
In-Depth Information
For our example, we first need to add another segment to work with. At the top of the script, create an
additional segment and position it in the center of the canvas element. Since this segment will now act as
the base, remove the initial positioning for segment0 as well:
var segment1 = new Segment(100, 20);
segment1.x = canvas.width / 2;
segment1.y = canvas.height / 2;
The next step is to find the point where segment0 will hit the target. Once again, this is the same point you
moved the segment to in the dragging examples, but don't move it, just store the position. So, you get this:
(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;
segment0.draw(context);
segment1.draw(context);
}());
We called the point tx , ty because it will be the target for segment1 to rotate to.
Next, you add the rotation code for segment1 to rotate to its target. This code is the same as the
calculation for segment0 , but it uses a different segment and different target:
(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);
Search WWH ::




Custom Search