Skip to content Skip to sidebar Skip to footer

Html5 Canvas - How To Draw A Line Over An Image Background?

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 th

Solution 1:

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

functiondrawbackground(canvas, context, onload){

    var imagePaper = newImage();


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

Solution 2:

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.

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

Solution 3:

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.

Solution 4:

Or you can try this:

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

Post a Comment for "Html5 Canvas - How To Draw A Line Over An Image Background?"