灯元
2016-07-21 10:07
<script>
var balls=[];
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
window.onload=function(){
canvas.width=800;
canvas.height=800;
for(var i=0;i<10;i++){
var aBall={x:Math.random()*canvas.width,
y:Math.random()*canvas.height,
r:Math.random()*50+20};
balls[i]=aBall;
}
draw();
canvas.addEventListener("click",detect);
}
function draw(){
for(var i=0;i<balls.length;i++){
context.beginPath();
context.arc(balls[i].x,balls[i].y,balls[i].r,0,Math.PI*2);
context.fillStyle="#058";
context.fill();
}
}
function detect(event){
var x=event.clientX-canvas.getBoundingClientRect().left;
var x=event.clientY-canvas.getBoundingClientRect().top;
for(var i=0;i<balls.length;i++){
context.beginPath();
context.arc(balls[i].x,balls[i].y,balls[i].r,0,Math.PI*2);
if(context.isPointInPath(x,y)){
context.fillStyle="red";
context.fill();
}
}
}
</script>
挖坟,lz解决了吗
这个代码,你写错了,这儿应该是y, var y=event.clientY-canvas.getBoundingClientRect().top;
Canvas绘图详解
72881 学习 · 422 问题
相似问题