Sir
Sir

Reputation: 8280

Draw circle line and then erase it

I have a simple script where by I am trying to draw a circle when a mouse goes over the canvas and it takes about 2000 milliseconds, when the mouse leaves the canvas it then erases the circle.

I got most of it working - it draws the circle correctly, but the mouse out does not fully work as it keeps restarting.

This is my code:

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();

I have made a fiddle of it too: http://jsfiddle.net/hru7xyfu/, to reproduce the error mouse over the canvas and wait for it to fully fill up then mouse out and you see the circle keeps restarting after it has fully erased it.

Where am i going wrong?

Upvotes: 3

Views: 121

Answers (1)

Josiah Krutz
Josiah Krutz

Reputation: 967

Try replacing

if(circle.curAngle == circle.endAngle){
    circle.animate = false;   
}

with:

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;   
}

The second if statement solves an issue where the circle grows too large (though you can't see it, because it starts overlapping itself)

Updated JSFiddle here: http://jsfiddle.net/hru7xyfu/2/

Upvotes: 2

Related Questions