HTML5 Canvas Drag-and-Drop
By Stephen Bucaro
to draw 2D shapes, graphics, animations, render bitmap images, and even create online
presentations and build dynamic browser games. In this article you'll learn how to use
drag-and-drop in your canvas projects.
The first step is to create the canvas element in the body of your webpage, the code for
this is shown below.
<canvas id="canvas" width="400" height="300" style="border-style:solid;">
In that code block I have declared some variables. The canvas variable will hold
a reference to the canvas element. The ctx variable will hold a reference to the
canvas' context. A context is a structure that holds the properties of the pen, fill
color, text, and so on that will be used by drawing commands.
var dragok = false;
The x and y variables contain the coordinates of any active actions. Just
like the computer screen itself, the coordinates of the canvas are in quadrant 4 of the
cartesian plane. The dragok variable is a flag that indicates if the drag object
should follow the mouse pointer.
x = 50;
y = 50;
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
canvas.onmousedown = down;
canvas.onmouseup = up;
window.onload = init;
coordinate position, assigns the canvas and context references, assigns function names to
the canvas onmousedown and onmouseup events, and sets an interval timer to
execute a draw function every 10 milliseconds. The last line attaches the init
function to the window.onload event.
ctx.clearRect(0, 0, 400, 300);
ctx.font = "18px verdana";
ctx.fillText("x=" + x + ",y=" + y,5,18);
to clear the canvas drawing area, draw a small circle (which will be the object that gets dragged),
and then writes the coordinates of the mouse pointer in the upper-right corner of the canvas.