JavaScript Answers

How to Set the Z-index of an HTML5 Canvas with JavaScript?

Spread the love

To set the z-index of an HTML5 canvas with JavaScript, we can use the canvas context’s globalCompositeOperation property.

For instance, we write:

<canvas style='width: 300px; height: 300px'></canvas>

to add a canvas element.

Then we write:

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
let cx = 50;

ctx.globalCompositeOperation = 'destination-over';

const randomColor = () => {
  return ('#' + Math.floor(Math.random() * 16777215).toString(16));

const drawCircle = () => {
  ctx.arc(cx, 50, 20, 0, Math.PI * 2);
  ctx.fillStyle = randomColor();

for (let i = 0; i < 5; i++) {
  cx += 20;

We get the canvas element with document.querySelector.

Then we call getContext to get the context.

Then we set globalCompositionOperator to 'destination-over' to draw the new shape behind the current shapes.

Next, we create the randomColor function to return a random color code.

Then we create the drawCircle function that calls ctx.arc to draw a circle.

The first 2 arguments are x and y coordinates of the center. The 3rd argument is the radius.

And the last argument is the angle of the arc, which is Math.PI * 2 since we want to draw a circle.

We call closePath to draw the arc.

fillStyle is the color of the circle.

And we call fill to fill the circle with the fill color.

Finally, we use the for loop to draw 5 circles.

Now we should see that the ones that are drawn later are behind the ones that are drawn earlier.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.