为什么这段代码不能在HTML5 Canvas上画一条简单的线?

时间:2014-01-04 00:07:02

标签: canvas html5-canvas

我有这个

ctx.globalAlpha = 1;
ctx.lineWidth = .5 ;
ctx.strokeStyle = '#2068A8';
ctx.moveTo(start.x, start.y);

current = {'x':start.x,'y':start.y}
function draw(){
    ctx.beginPath();
    current.y+= 50;
    //ctx.clearRect(0,0,canvas.width, canvas.height);
    ctx.lineTo( current.x, current.y  );
    ctx.moveTo( current.x, current.y  );
    ctx.stroke();
    if (current.y < finish.y) {
        setTimeout( draw, drawTime);
    }
}
setTimeout( draw, drawTime);

但没有画线。是什么给了什么?

1 个答案:

答案 0 :(得分:0)

起初我以为这是导致我出现问题的循环,但是当你在其他所有东西之前设置ctx.beginPath()时,它会运行起来。这是改变的答案

function drawLineSlowly(from, to){
var start = from || {'x':200,'y':0}, finish = {'x':225,'y':document.body.scrollHeight},
     drawTime = 2, current = 0;

ctx.globalAlpha = 1;
ctx.lineWidth = .5 ;
ctx.strokeStyle = '#2068A8';
ctx.beginPath();


ctx.moveTo(start.x, start.y);



current = {'x':start.x,'y':start.y}

function draw(){


    current.y+= 50;
    //ctx.clearRect(0,0,canvas.width, canvas.height);
    ctx.lineTo( current.x, current.y  );
    ctx.moveTo( current.x, current.y  );

    ctx.stroke();

    if (current.y < finish.y) {
    setTimeout( draw, drawTime);
    }

}

setTimeout( draw, drawTime);

}