我有一个简单的脚本,我试图在鼠标经过 Canvas 时绘制一个圆圈,这需要大约 2000 毫秒,当鼠标离开 Canvas 时,它会删除圆圈。
我的大部分工作正常 - 它正确地绘制了圆圈,但是鼠标移开并不能完全工作,因为它不断重新启动。
这是我的代码:
canvas.addEventListener('mouseover',fill,false);
canvas.addEventListener('mouseout',erase, false);
function fill(){
circle.animate = true;
circle.direction = 1;
}
function erase(){
circle.animate = true;
circle.direction = 0;
}
function maths(){
if(circle.animate == true){
var amount = circle.vector * deltaTime;
if(circle.direction == 1){
circle.curAngle += amount;
}else if(circle.direction == 0){
circle.curAngle -= amount;
}
if(circle.curAngle % 2 == 0){
circle.curAngle = 0;
}
if(circle.curAngle == circle.endAngle){
circle.animate = false;
}
}
}
function draw(){
deltaTime = Date.now() - frame;
frame = Date.now();
maths();
context.clearRect(0,0,canvas.width,canvas.height);
context.beginPath();
context.arc(canvas.width/2, canvas.height/2, 100, circle.startAngle * Math.PI, circle.curAngle * Math.PI,false);
context.lineWidth = 2;
context.strokeStyle = 'blue';
context.stroke();
setTimeout(draw,1);
}
frames = Date.now();
draw();
我也做了一个 fiddle : http://jsfiddle.net/hru7xyfu/ ,要重现错误,请将鼠标悬停在 Canvas 上并等待它完全填满,然后将鼠标移开,您会看到圆圈在完全删除后不断重新启动。
我哪里错了?
最佳答案
尝试替换
if(circle.curAngle == circle.endAngle){
circle.animate = false;
}
与:
if(circle.curAngle < circle.endAngle){
circle.curAngle = circle.endAngle
circle.animate = false;
}
if(circle.curAngle > circle.endAngle + 2){
circle.curAngle = circle.endAngle + 2
circle.animate = false;
}
第二个 if 语句解决了圆变得太大的问题(虽然你看不到它,因为它开始 self 重叠)
在此处更新了 JSFiddle: http://jsfiddle.net/hru7xyfu/2/
关于javascript - 画圆线然后擦掉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33161522/