HTML5画布 - 如何绘制在图像背景中的线?(HTML5 Canvas - How to Draw

2019-06-24 12:17发布

我想画的图像背景之上的线 - 在HTML5画布。 然而总是行获取绘制图像后面。 其实行被抽中,然后将照片拿得出 - 不管我如何调用该函数。

如何把线图像的顶部?

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

Answer 1:

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

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


Answer 2:

为了更有效的,假设你打算做这一行或行的多个重绘,将设置CSS background-image的画布是你的形象。

<canvas style="background-image:url('images/main_timerand3papers.png');"></canvas>


Answer 3:

图像的onload更改为这样的事情:

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

然后确保你删除早期调用drawLines

重要带走该解决方案,是对onload功能将在未来某个时候,而drawLines功能立即执行执行。 嵌套它们时,你必须非常小心你如何组织你的回调,尤其是。



Answer 4:

或者你也可以试试这个:

drawbackground(canvas, context);
context.globalCompositeOperation = 'destination-atop';
drawlines(canvas, context);


文章来源: HTML5 Canvas - How to Draw a line over an image background?