18

我正在尝试在图像背景上画一条线 - 在 HTML5 Canvas 中。然而,总是在图像后面画线。实际上,首先绘制线条,然后绘制图片 - 无论我如何调用函数。

如何将线条置于图像顶部?

var canvas = document.getElementById("myCanvas");
        var context = canvas.getContext("2d");
            context.clearRect(0, 0, canvas.width, canvas.height);
drawbackground(canvas, context); 
drawlines(canvas, context); 


function drawbackground(canvas, context){

    var imagePaper = new Image();


        imagePaper.onload = function(){


            context.drawImage(imagePaper,100, 20, 500,500);
        };

      imagePaper.src = "images/main_timerand3papers.png";
}



function drawlines(canvas, context){


            context.beginPath();
            context.moveTo(188, 130);
            context.bezierCurveTo(140, 10, 388, 10, 388, 170);
            context.lineWidth = 10;
            // line color
            context.strokeStyle = "black";
            context.stroke();
}
4

4 回答 4

20

完全未经测试的代码,但你尝试过这样的事情吗?

function drawbackground(canvas, context, onload){

    var imagePaper = new Image();


        imagePaper.onload = function(){


            context.drawImage(imagePaper,100, 20, 500,500);
            onload(canvas, context);
        };

      imagePaper.src = "images/main_timerand3papers.png";
}

然后像这样调用方法...

 drawbackground(canvas, context, drawlines);
于 2012-05-16T17:38:36.547 回答
7

为了提高效率,假设您要对这条或多条线进行多次重绘,请将background-image画布的 CSS 设置为您的图像。

<canvas style="background-image:url('images/main_timerand3papers.png');"></canvas>
于 2012-05-16T18:47:32.947 回答
6

将您的图像 onload 更改为以下内容:

imagePaper.onload = function () {
    context.drawImage( imagePaper, 100, 20, 500, 500 );
    drawLines( canvas, context );
};

然后确保删除之前对drawLines.

该解决方案的重要内容是该onload函数将在将来的某个时间执行,而 drawLines 函数将立即执行。您必须始终小心构建回调的方式,尤其是在嵌套它们时。

于 2012-05-16T17:46:29.253 回答
4

或者你可以试试这个:

drawbackground(canvas, context);
context.globalCompositeOperation = 'destination-atop';
drawlines(canvas, context);
于 2013-02-26T08:54:32.677 回答