HTML5 Canvas - How to Draw a line over an image ba

2019-01-17 21:59发布

I am trying to draw a line on top of an image background - in an HTML5 Canvas . However always the line gets drawn behind the image . Actually the line gets drawn first and then the pictures get drawn - irrespective of how I call the functions.

How do I bring the line to the top of the image ?

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条回答
看我几分像从前
2楼-- · 2019-01-17 22:32

Change your image onload to something like this:

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

Then make sure you remove the earlier call to drawLines.

The important take away to this solution, is that the onload function will be executed sometime in the future, whereas the drawLines function is executed immediately. You must always be careful of how you structure your callbacks, especially when nesting them.

查看更多
甜甜的少女心
3楼-- · 2019-01-17 22:35

Totally untested code, but did you tried something like this?

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

and then call the method like this...

 drawbackground(canvas, context, drawlines);
查看更多
神经病院院长
4楼-- · 2019-01-17 22:38

Or you can try this:

drawbackground(canvas, context);
context.globalCompositeOperation = 'destination-atop';
drawlines(canvas, context);
查看更多
在下西门庆
5楼-- · 2019-01-17 22:44

To be more efficient, assuming you are going to be doing multiple redraws of this line or lines, would be to set the CSS background-image of the canvas to be your image.

<canvas style="background-image:url('images/main_timerand3papers.png');"></canvas>
查看更多
登录 后发表回答