<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>canvas</title> <style type="text/css"> canvas { border: 1px solid red; } </style> </head> <body> <canvas id="myCanvas" width="600px" height="400px"> 您的浏览器不支持canvas </canvas> <script type="text/javascript"> var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); var posx = 0, posy = 0, dir = 1, isMouseInRect = false; canvas.onmousemove = function(e){ var mouseX = e.offsetX; var mouseY = e.offsetY; if(mouseX > posx && mouseY <posx +50 && mouseY > posy && mouseY < posy+ 50){ isMouseInRect = true; }else{ isMouseInRect = false; } } setInterval(function() { if(!isMouseInRect){ posx += 10 * dir; } //clearRect清空画布的一个矩形区域 ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillRect(posx, posy, 50, 50); if(posx + 50 >= canvas.width){ dir = -1; }else if(posx <= 0){ dir = 1; } },100); </script> </body> </html>