标签:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <canvas id="canvas" style="margin:0 auto;border:1px #ddd solid"> The current browser does not support Canvas, can replace the browser a try! </canvas> <script> var canvas = document.getElementById(‘canvas‘); var context = canvas.getContext(‘2d‘); var balls = []; window.onload = function(){ // var canvas = document.getElementById(‘canvas‘); canvas.width = 1024; canvas.height = 768; if(canvas.getContext(‘2d‘)){ // var context = canvas.getContext(‘2d‘); 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("mousemove",detect); }else{ alert(‘当前游览器不支持Canvas,请更换游览器后再试!‘); } } function draw(x,y){ context.clearRect(0,0,canvas.width,canvas.height); 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"; 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> </body> <script> /*总结 //判断事件是不是在canvas内 context.isPointInPath(x,y) */ </script> </html>
标签:
原文地址:http://www.cnblogs.com/cynthia-wuqian/p/4989156.html