不啰嗦上代码:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> </head> <body> <canvas id="gameCanvas" width="500px" height="300px"></canvas> <script> var cvs = document.getElementById('gameCanvas'); var ctx = cvs.getContext('2d'); //绘制黑色背景 ctx.fillStyle = 'black'; ctx.fillRect(0, 0, 500,300); //绘制红色矩形 ctx.fillStyle = 'red'; ctx.fillRect(100, 100, 100,100); //记录矩形的位置 var posX = 100; var posY = 100; cvs.onmousedown = function(e){ var x = e.clientX - posX; var y = e.clientY - posY; //判断鼠标是否点击在矩形内 if(e.clientX >= posX + this.offsetLeft && e.clientX <= posX + 100 + this.offsetLeft && e.clientY >= posY + this.offsetTop && e.clientY <= posY + 100 + this.offsetTop){ document.onmousemove = function(e){ //ctx.clearRect(posX, posY, 100,100); //鼠标拖动时重绘黑色背景 ctx.fillStyle = 'black'; ctx.fillRect(0, 0, 500,300); //鼠标拖动时重绘红色矩形 ctx.fillStyle = 'red'; ctx.fillRect(e.clientX-x, e.clientY-y, 100,100); //记录矩形的位置 posX = e.clientX-x; posY = e.clientY-y; }; document.onmouseup = function(){ document.onmousemove = null; }; } }; </script> </body> </html>