HTML and CSS Reference
In-Depth Information
Combining dragging with motion code
Now you know pretty much everything about simple dragging and dropping on the canvas. But in the
process, we've reverted back to a static object that just sits there unless you drag it. To make it interesting,
let's add some velocity, acceleration, and bouncing.
You already have a nice setup for velocity, gravity, and bouncing in the 05-bouncing-2.html example
from the previous chapter, so that will be our starting point. It seems logical to simply add your drag-and-
drop code to that code, so let's try it. You should end up with something like this document ( 04-drag-and-
move-1.html ):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Drag and Move 1</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script src="ball.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
mouse = utils.captureMouse(canvas),
ball = new Ball(),
vx = Math.random() * 10 - 5,
vy = -10,
bounce = -0.7,
gravity = 0.2,
isMouseDown = false;
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
canvas.addEventListener('mousedown', function () {
if (utils.containsPoint(ball.getBounds(), mouse.x, mouse.y)) {
isMouseDown = true;
canvas.addEventListener('mouseup', onMouseUp, false);
canvas.addEventListener('mousemove', onMouseMove, false);
}
}, false);
function onMouseUp () {
isMouseDown = false;
canvas.removeEventListener('mouseup', onMouseUp, false);
canvas.removeEventListener('mousemove', onMouseMove, false);
}
function onMouseMove (event) {
 
Search WWH ::




Custom Search