var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var WIDTH = 400;
var HEIGHT = 300;
function Box(ctx_, id_)
{
this.ctx = ctx_;
this.x = 75;
this.y = 50;
this.dx = 15;
this.dy = 15;
this.id = id_;
this.dragok = false;
}
Box.prototype.create = function() {
this.ctx.beginPath();
this.ctx.rect(this.x,this.y,this.dx,this.dy);
this.ctx.closePath();
this.ctx.fill();
}
Box.prototype.cleare = function() {
this.ctx.beginPath();
this.ctx.clearRect(this.x, this.y, this.dx, this.dy);
this.ctx.closePath();
this.ctx.fill();
}
Box.prototype.getX = function() {
return (this.x + canvas.offsetLeft);
}
Box.prototype.getY = function() {
return (this.y + canvas.offsetTop);
}
Box.prototype.isFocus = function(mX,mY) {
if(mX>this.getX() && mY>this.getY() && mX<(this.getX() + this.dx) && mY<(this.getY() + this.dy))
return true;
else
return false;
}
function getRandomArbitary(min, max)
{
return Math.random() * (max - min) + min;
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function GetId(mX,mY)
{
for(p in rect)
{
if(rect[p].isFocus(mX,mY))
{
return rect[p].id;
}
}
}
function draw()
{
clear();
for(p in rect)
{
rect[p].create();
}
}
function Move(e){
var id = GetId(e.pageX,e.pageY);
rect[id].x = e.pageX - canvas.offsetLeft;
rect[id].y = e.pageY - canvas.offsetTop;
}
function Up(){
canvas.onmousemove = null;
}
function Down(){
canvas.onmousemove = Move;
}
var rect = new Array(3);
for(var i=0; i<3 ; i++)
{
rect[i] = new Box(ctx,i);
rect[i].x = getRandomArbitary(0, 300);
rect[i].y = getRandomArbitary(0, 260);
rect[i].create();
}
setInterval(draw, 10);
canvas.onmousedown = Down;
canvas.onmouseup = Up;
Немного переработал скрипт. Есть баги небольшие, отладишь сам.