HTML and CSS Reference
In-Depth Information
In the next example, we remove some of the duplicated code by creating a new function named drag . The
parameters for this are the segment to drag and the x, y point to drag to. Then you move segment0 to
point mouse.x , mouse.y and segment1 to point segment0.x , segment0.y . Here's the complete code
listing for document 03-two-segment-drag.html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Two Segment Drag</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script src="segment.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
mouse = utils.captureMouse(canvas),
segment0 = new Segment(100, 20),
segment1 = new Segment(100, 20);
function drag (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;
segment.x = xpos - w;
segment.y = ypos - h;
}
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
drag(segment0, mouse.x, mouse.y);
drag(segment1, segment0.x, segment0.y);
segment0.draw(context);
segment1.draw(context);
}());
};
</script>
</body>
</html>
Search WWH ::




Custom Search