HTML5 – Canvas Drag & Drop

A simple example of Drag & Drop in HTML5 Canvas

by davidbarszczak

HTML

<canvas id='myCanvas' width="400" height="480">

JavaScript

/* Keys.js */
var Keys = {Left:false,Right:false,MouseDown:false};

// Keyboard Controls
window.onkeydown = function() {
	switch(event.keyCode) {
		case 37:
			Keys.Left = true;
		break;
		case 39:
			Keys.Right = true;
		break;
	}
}

window.onkeyup = function() {
	switch(event.keyCode) {
		case 37:
			Keys.Left = false;
		break;
		case 39:
			Keys.Right = false;
		break;
	}
}

/* Player.js */
var Player = function(){

this.x = 100;
this.y = 100;
this.h = 25;
this.w = 25;
this.direction="r";

this.update = function() {
	// Update code goes here.
	if ( Keys.Left == true && this.x >=0 )  this.x = this.x - 4;
	if ( Keys.Right == true && (this.x+this.w) <= Game.canvas.width ) this.x = this.x + 4;
}

this.draw = function() {
	// Draw code goes here.
	Game.ctx.fillStyle="#FF0000";
	Game.ctx.fillRect(this.x,this.y,this.w,this.h);
}

};

/* Game.js */

var Game = { };
var Player1 = new Player();

// Game Variables
Game.canvas = document.getElementById('myCanvas');
Game.ctx = myCanvas.getContext('2d');
Game.fps = 30;

// Core Methods
Game.run = function() {
	// Run code goes here.
	Game.draw();
	Game.update();
}

Game.update = function() {
	// Update code goes here.
	Player1.update();
}

Game.draw = function() {
	// Draw code goes here.
	Game.clear();
	Player1.draw();
}

Game.clear = function() {
	// Clear the canvas.
	Game.ctx.fillStyle="#FFFFFF";
	Game.ctx.fillRect(0,0,Game.canvas.width,Game.canvas.height);
}

Game.canvas.onmousedown = function(e) {
	if ( e.offsetX >= Player1.x && e.offsetX <= (Player1.x + Player1.w) && e.offsetY >= Player1.y && e.offsetY <= (Player1.y + Player1.h) ) {
		Keys.MouseDown = true;
	}
}

Game.canvas.onmouseup = function(e) {
	Keys.MouseDown = false;
}

Game.canvas.onmousemove = function(e) {
	if ( Keys.MouseDown == true ) {
		Player1.x = e.offsetX;
		Player1.y = e.offsetY;
		console.log(Player1.y);
	}
}

Game._intervalId = setInterval(Game.run, 1000 / Game.fsp);