87,907
社区成员
发帖
与我相关
我的任务
分享
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<canvas id="canvas" width="500" height="500" style="background: #e4e4e4"></canvas>
</body>
</html>
<script>
var canvas =document.getElementById('canvas');
var context = canvas.getContext('2d');
var rects =[{ x:50, y:50,width:100,height:100 },
{x:200, y:200,width:100,height:100} ]
window.onload = function(){
draw();
canvas.addEventListener("mousemove", detect);
}
function draw(x,y){
context.clearRect(0,0,canvas.width,canvas.height);
for(var i=0;i<rects.length;i++){
context.beginPath();
context.rect( rects[i].x, rects[i].y, rects[i].width, rects[i].height);
if(context.isPointInPath(x,y)){
context.fillStyle = 'red';
}else{
context.fillStyle = '#058';
}
context.fill();
}
}
function detect(event){
var x = event.clientX - canvas.getBoundingClientRect().left;
var y = event.clientY - canvas.getBoundingClientRect().top;
draw(x,y);
}
</script>