Welcome to Bucaro TecHelp!

Bucaro TecHelp
Maintain Your Computer and Use it More Effectively
to Design a Web Site and Make Money on the Web

About Bucaro TecHelp About BTH User Agreement User Agreement Privacy Policy Privacy Site Map Site Map Contact Bucaro TecHelp Contact RSS News Feeds News Feeds

Holiday Gift Guide
Holiday Gift Guide

HTML5 Canvas Drag-and-Drop

The HTML5 canvas element creates a sketchpad area on a webpage where you can use JavaScript 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;">
</canvas>

The next step is to create a JavaScript code block in the head section of your webpage. 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.

<script>

var canvas;
var ctx;
var x;
var y;
var dragok = false;

</script>

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.

function init()
{
  x = 50;
  y = 50;
  canvas = document.getElementById("canvas");
  ctx = canvas.getContext("2d");
  canvas.onmousedown = down;
  canvas.onmouseup = up;
  setInterval(draw, 10);
}

window.onload = init;

Next, in the JavaScript code block, define an init function that initializes the 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.

function draw()
{
  ctx.clearRect(0, 0, 400, 300);

  ctx.beginPath();
  ctx.arc(x,y,4,0,2*Math.PI);
  ctx.stroke();

  ctx.font = "18px verdana";
  ctx.fillText("x=" + x + ",y=" + y,5,18);
}

Next, in the JavaScript code block, define a draw function. It uses context methods 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.

RSS Feed RSS Feed

Follow Stephen Bucaro Follow @Stephen Bucaro



Fire HD
[Site User Agreement] [Privacy Policy] [Site map] [Search This Site] [Contact Form]
Copyright©2001-2017 Bucaro TecHelp 13771 N Fountain Hills Blvd Suite 114-248 Fountain Hills, AZ 85268