HTML and CSS Reference
In-Depth Information
segment0.rotation = Math.atan2(dy, dx);
segment0.draw(context);
}());
};
</script>
</body>
</html>
Figure 14-1 shows the result. Test this and watch how the segment follows the mouse around. Even if the
segment is too far away, you can see how it seems to be reaching for the mouse.
Figure 14-1. A single segment reaching toward the mouse
Dragging with a Single Segment
Now, let's try dragging. The first part of the dragging method is the same as the reaching method: You
rotate the object toward the mouse. But then you go a step further and move the segment to a position that
places the second pivot point exactly where the mouse is. To do that, you need to know the distance
between the two pins on each axis. You can get this from the difference (on each axis) between the
segment's getPin() point and its actual x, y location—we call these w and h . Then subtract w and h from
the current mouse position, and you know where to put the segment. Here's the drawFrame function from
02-one-segment-drag.html , which is the only part that has changed from the previous example:
(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;
segment0.x = mouse.x - w;
segment0.y = mouse.y - h;
 
Search WWH ::




Custom Search