<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var rect1 = {
x:100,
y:100,
w:50,
h:50,
color:'palegreen'
}
var rect2 = {
x:200,
y:200,
w:100,
h:100,
color:'deeppink'
}
var rects = [rect1,rect2];
var index = -1;
function drawRect(){
ctx.clearRect(0,0,canvas.width,canvas.height);
for (var i = 0; i < rects.length; i++) {
ctx.beginPath();
ctx.fillStyle = rects[i].color;
ctx.rect(rects[i].x,rects[i].y,rects[i].w,rects[i].h);
ctx.fill();
if (arguments.length) {
if (ctx.isPointInPath(arguments[0],arguments[1])) {
index = i;
}
}
}
}
drawRect();
canvas.onmousedown = function(e){
var ev = e || window.event;
// 鼠标坐标
var x = ev.clientX;
var y = ev.clientY;
drawRect(x,y);
if (index == -1) {
return;
}
var oldX = x - rects[index].x;
var oldY = y - rects[index].y;
canvas.onmousemove = function(e){
var ev = e || window.event;
rects[index].x = ev.clientX - oldX;
rects[index].y = ev.clientY - oldY;
drawRect();
}
canvas.onmouseup = function(){
index = -1;
canvas.onmousemove = null;
}
}
</script>
</body>
</html>