canvas监听画布上的内容被点击(仅仅适用于,画图上的内容较少(因为需要遍历)
canvas监听画布上的内容被点击(仅仅适用于,画图上的内容较少(因为需要遍历)
var cannvas=document.getElementById("cannvas");
var contenxt =cannvas.getContext("2d");
一、获取鼠标停留在画布上的区域
var x = event.clientX - cannvas.getBoundingClientRect().left;//鼠标在当前画布上的位置
var y = event.clientY - cannvas.getBoundingClientRect().top;
二、通过canvas画布添加监听事件(我这里面监听的是鼠标抬起,自取其他方式)
cannvas.addEventListener("mouseup",detect);
鼠标抬起,触发函数detect,在这个函数里面去遍历 所有画内要要被监听的元素。使用isPointInPath,判断停留的点是否在元素内部,触发
function detect(event){
console.log("鼠标被提起了");
var x = event.clientX - cannvas.getBoundingClientRect().left;//鼠标在当前画布上的位置
var y = event.clientY - cannvas.getBoundingClientRect().top;
for (var i=0; i<balls.length; i++) {
contenxt.beginPath();
contenxt.arc(balls[i].x, balls[i].y, balls[i].r, 0, Math.PI*2);
if(contenxt.isPointInPath(x,y)){
contenxt.fillStyle='red';
contenxt.fill();
}
}
}
附所有的代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>监听点击圆圈区域内变色</title>
</head>
<body>
<div>
<canvas ref="gridRef3" id="cannvas" width="1000" height="1000"></canvas>
</div>
<script>
var balls=[];
var cannvas=document.getElementById("cannvas");
var contenxt =cannvas.getContext("2d");
window.onload= function(){
for(var i=0;i<10;i++){
var aBalls={
x:Math.random()*cannvas.width,
y:Math.random()*cannvas.height,
r:Math.random()*50+20
};
balls[i]=aBalls;
}
draw();
cannvas.addEventListener("mouseup",detect);
}
function draw(){
for(var i=0;i<balls.length; i++){
contenxt.beginPath();
contenxt.arc(balls[i].x ,balls[i].y ,balls[i].r ,0 ,Math.PI*2);
contenxt.fillStyle= "#058";
contenxt.fill();
}
}
function detect(event){
console.log("鼠标被提起了");
var x = event.clientX - cannvas.getBoundingClientRect().left;//鼠标在当前画布上的位置
var y = event.clientY - cannvas.getBoundingClientRect().top;
for (var i=0; i<balls.length; i++) {
contenxt.beginPath();
contenxt.arc(balls[i].x, balls[i].y, balls[i].r, 0, Math.PI*2);
if(contenxt.isPointInPath(x,y)){
contenxt.fillStyle='red';
contenxt.fill();
}
}
}
</script>
</body>
</html>