<canvas id="canvas"></canvas><br />
<input type="checkbox" id="offset">Check to use offset values.
JavaScript
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
c.width = 300;
c.height = 200;
var myRectangle = {
x: 50,
y: 130,
w: 100,
h: 50,
drag: false
}
var mouseX = 0;
var mouseY = 0;
var mouseOffset = {x: 0, y:0}; // How far from the rectangle corner are we clicking?
var background = "#0099CC";
c.addEventListener("mousemove",mouseMove,false);
c.addEventListener("mousedown",mouseDown,false);
c.addEventListener("mouseup",mouseUp,false);
//Getting the
function getMouseCoordinates() {
event = event || window.event;
mouseX = event.pageX - c.offsetLeft,
mouseY = event.pageY - c.offsetTop;
}
//This is what should be done while moving the mouse
function mouseMove(event) {
getMouseCoordinates();
if (myRectangle.drag) {
myRectangle.x = mouseX-mouseOffset.x;
myRectangle.y = mouseY-mouseOffset.y;
}
}
// This is what should happen when mouse button is pressed down
function mouseDown() {
if (mouseX > myRectangle.x &&
mouseX < myRectangle.x+myRectangle.w &&
mouseY > myRectangle.y &&
mouseY < myRectangle.y + myRectangle.h) {
if (document.getElementById("offset").checked) {
mouseOffset.x = mouseX-myRectangle.x;
mouseOffset.y = mouseY-myRectangle.y;
}
else {
mouseOffset.x = 0;
mouseOffset.y = 0;
}
myRectangle.drag = true;
background = "#66FF99";
}
}
// This is what should happen when mouse button is released back up
function mouseUp() {
myRectangle.drag = false;
background = "#0099CC";
}
function draw() {
// Clear the canvas before painting.
ctx.fillStyle="#F0F0F0";
ctx.fillRect(0,0,c.width,c.height);
//Drawing the rectangle
ctx.fillStyle=background;
ctx.fillRect(myRectangle.x,myRectangle.y,myRectangle.w,myRectangle.h);
ctx.strokeRect(myRectangle.x,myRectangle.y,myRectangle.w,myRectangle.h);
// Loop the...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.