How to draw a line over an image background with HTML5 canvas and JavaScript?

Sometimes, we want to draw a line over an image background with HTML5 canvas and JavaScript.

In this article, we’ll look at how to draw a line over an image background with HTML5 canvas and JavaScript.

How to draw a line over an image background with HTML5 canvas and JavaScript?

To draw a line over an image background with HTML5 canvas and JavaScript, we can call some canvas methods.

For instance, we write:

<canvas width='200' height='300'></canvas>

to add a canvas.

Then we write:

const canvas = document.querySelector("canvas")
const context = canvas.getContext("2d")
const image = new Image()
image.onload = () => {
  context.drawImage(image, 100, 20, 500, 500);
  context.beginPath();
  context.moveTo(188, 130);
  context.bezierCurveTo(140, 10, 388, 10, 388, 170);
  context.strokeStyle = "black";
  context.stroke();
}
image.src = 'https://picsum.photos/200/300'

to select the canvas with querySelector.

Then we create an img element with Image.

We set image.onload to a function that draws image onto the canvas with drawImage.

Then we use beginPath to start drawing.

moveTo moves to the location we want to draw.

besizeCurveTo draws a bezier curve. The first 4 arguments are the x and y coordinates of the first 2 control points.

And the last 2 arguments are the x and y coordinates of the end point.

strokeStyle sets the stroke.

And stroke draws the line.

Conclusion

To draw a line over an image background with HTML5 canvas and JavaScript, we can call some canvas methods.