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();
}
To draw a line on a canvas, you use the following steps: First, create a new line by calling the beginPath() method. Second, move the drawing cursor to the point (x,y) without drawing a line by calling the moveTo(x, y) . Finally, draw a line from the previous point to the point (x,y) by calling the lineTo(x,y) method.
The function we use for drawing an image onto a canvas is the drawImage() function. This function draws an image, canvas, or video onto the canvas. It can also draw parts of an image, and/or increase/reduce the image size.
Adding Borders in Canvas Canvas allows you to add borders to an image directly inside Canvas using HTML code. When editing a page with an image, click on HTML Editor in the upper corner. Inside of the HTML code of the page, look for the <img> tag and add this code inside of it, before the src= section.
The lineTo() method adds a new point and creates a line TO that point FROM the last specified point in the canvas (this method does not draw the line). Tip: Use the stroke() method to actually draw the path on the canvas. JavaScript syntax: context.lineTo(x,y);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With