canvas中交互isPointInPath()方法
canvas有一个交互性很强的API——isPointInPath(),isPointInPath(x,y)方法用来检测指定点是在路径内还是在路径外。如果在当前路径中,则返回true,否则返回false
下面是一个canvas交互的实例,点击蓝色的小圆,可变成红色
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <canvas id="drawing" style="border:1px solid black"> <p>The canvas element is not supported!</p> </canvas> <script> var drawing = document.getElementById('drawing'); if(drawing.getContext){ var cxt = drawing.getContext('2d'); var H=150,W=300; var balls = []; var NUM = 5; for(var i = 0; i < NUM; i++){ var tempBall = { x:Math.floor(Math.random()*W), y:Math.floor(Math.random()*H), r:Math.floor(Math.random()*40+20) } balls[i] = tempBall; draw(); drawing.addEventListener('click',fnDetect); } function draw(){ for(var i = 0; i < balls.length; i++){ cxt.beginPath(); cxt.arc(balls[i].x,balls[i].y,balls[i].r,0,Math.PI*2); cxt.fillStyle = '#058'; cxt.fill(); } } function fnDetect(e){ e = e || event; var x = e.clientX - drawing.getBoundingClientRect().left; var y = e.clientY - drawing.getBoundingClientRect().top; for(var i = 0; i < balls.length; i++){ cxt.beginPath(); cxt.arc(balls[i].x,balls[i].y,balls[i].r,0,Math.PI*2); if(cxt.isPointInPath(x,y)){ cxt.fillStyle = 'red'; cxt.fill(); } } } } </script> </body> </html>
本站声明:网站内容来源于网络,如有侵权,请联系我们https://www.qiquanji.com,我们将及时处理。
微信扫码关注
更新实时通知