Betsey
2016-03-07 14:27
window.onload = function() { var canvas = document.getElementById("canvas"); var c = canvas.getContext('2d'); canvas.width = 1200; canvas.height = 800; var ball = []; for (var i = 0; i < 10; i++) { var aBall = { x: Math.random() * canvas.width, y: Math.random() * canvas.height, r: Math.random() * 30 + 10 } ball[i] = aBall; } draw(c); canvas.addEventListener('click', detect); function draw(c) { for (var i = 0; i < ball.length; i++) { c.beginPath(); c.arc(ball[i].x, ball[i].y, ball[i].r, 0, 2 * Math.PI); c.fillStyle = "#058"; c.fill(); } } function detect(event){ var x=event.clientX-canvas.getBoundingClientRect().left; var y=event.clientY-canvas.getBoundingClientRect().top; for(var i=0;i<ball.length;i++){ c.beginPath(); c.arc(ball[i].x, ball[i].y, ball[i].r, 0, 2 * Math.PI); c.closePath(); } if(c.isPointInPath(x,y)){ c.fillStyle='red'; c.fill(); } } }
if(c.isPointInPath(x,y)) 这个判断应该在for循环里面
Canvas绘图详解
72885 学习 · 422 问题
相似问题