我编写了一个代码,在画布中随机生成60个圆圈,如何处理按下的事件onclick
循环消失和生成后的另一个循环?哪一个可能是最好的解决方案?守则是:
var canvas, ctx;
var circles = [];
var selectedCircle;
var vel=200;
function Circle(x, y, radius){
this.x = x;
this.y = y;
this.radius = radius;
}
function clear() { // clear canvas
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
function drawCircle(ctx, x, y, radius) {
var color = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
function generate(){
canvas = document.getElementById('my');
ctx = canvas.getContext('2d');
var circleRadius = 25;
var width = canvas.width;
var height = canvas.height;
var timer, j = 0;
var circlesCount = 60;
for (var i=0; i<circlesCount; i++) {
var x = Math.random()*width;
var y = Math.random()*height;
circles.push(new Circle(x,y,circleRadius));
}
timer = window.setInterval(function()
{
if(j==60)
{
clear();
return;
}
drawCircle(ctx, circles[j].x, circles[j].y, circles[j].radius);
// go to next circle
j++;
}, vel);
}
发布于 2015-09-27 11:46:51
最好的解决方案是使用svg,它将创建SVGElements,每个SVGElements都有自己的事件接口。
现在,用画布做这件事并不是不可能的,但正如@VickyGonsalves所提到的,您必须存储所有的圆圈位置,计算它们的表面位置,并检查单击事件的clientX和clientY是否在其中之一中,然后重新绘制没有单击的所有圆圈位置。
但是,新的Path2D接口允许存储路径并在以后重用它们,或者将它们用于上下文的方法,如fill()
和isPointInPath()
。
因此,这里有一个使用Path2d()
构造函数的简单解决方案,不支持IE,也不支持Safari。。
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
circles = [];
document.body.appendChild(canvas);
canvas.width = 500;
canvas.height = 500;
function Circle(x, y, radius) {
var c = new Path2D();
c.arc(x, y, radius, 0, Math.PI * 2);
return c;
}
function init() {
ctx.strokeStyle = 'white';
for (var i = 0; i < 60; i++) {
circles.push(Circle((Math.random() * (canvas.width - 40)) + 20, (Math.random() * (canvas.height - 40)) + 20, 20));
ctx.fill(circles[i], "nonzero");
ctx.stroke(circles[i], "nonzero");
}
}
function clickHandler(e) {
var r = canvas.getBoundingClientRect(),
x = e.clientX - r.left,
y = e.clientY - r.top,
i;
for (i = circles.length - 1; i >= 0; --i) {
console.log(i);
if (ctx.isPointInPath(circles[i], x, y, 'nonzero')) {
circles.splice(i, 1);
}
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (i = 0; i < circles.length; i++) {
ctx.fill(circles[i], "nonzero")
ctx.stroke(circles[i], "nonzero");
}
}
canvas.addEventListener('click', clickHandler, false);
init();
https://stackoverflow.com/questions/32736999
复制相似问题