javascript - 画圆线然后擦掉

标签 javascript animation math canvas

我有一个简单的脚本,我试图在鼠标经过 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/

相关文章:

在客户端将 PHP 转为 JSON

java游戏-光滑的滚动条-玩家不能移动

ios - 在呈现 VC 时保持动画 View 的最后位置

jquery - -webkit-transition/-moz-transition 与 jQuery

c - 我们如何比较数量小于

iphone - 从 CATransform3D 获取 'scale'

javascript - IE11对象不支持属性或方法'Symbol(Symbol.iterator)_a.2p3bca3ct9h

javascript - 脚本函数不会打开模态

javascript - 赋值表达式的结果总是右侧的值吗?

c# - 如何在 C# 中计算 fmod?