Canvas drawImage z-index

32 views Asked by At
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    body {
        padding: 0;
        margin: 0;
    }
</style>

<body>
    <canvas></canvas>
</body>
<script>
    var canvas = document.querySelector('canvas')
    canvas.width = 1920;
    canvas.height = 1080;

    var ctx = canvas.getContext('2d')

    initial();
    function initial() {
        ctx.fillStyle = 'red';
        ctx.rect(10, 10, 100, 100)
        ctx.fill();

        let bgImg = new Image();
        bgImg.onload = drawBgImg;
        bgImg.src = 'https://media.istockphoto.com/id/1146517111/photo/taj-mahal-mausoleum-in-agra.jpg?s=612x612&w=0&k=20&c=vcIjhwUrNyjoKbGbAQ5sOcEzDUgOfCsm9ySmJ8gNeRk=';

    }

    function drawBgImg() {
        ctx.drawImage(this, 0, 0, 60, 60)
    }
</script>

</html>

enter image description here

I created a rect and draw image from url, now i want to use image like background, red rect should be on top like foreground. but so many ways i tred drawimage code moved to top bottom but it is always on foreground only. i want to set it for background.

is there any way like z-index or any other solution please.

1

There are 1 answers

0
afrikazil On

Objects drawn later will always overlap layers drawn earlier. You need draw red square after background;

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    body {
        padding: 0;
        margin: 0;
    }
</style>

<body>
    <canvas></canvas>
</body>
<script>
    var canvas = document.querySelector('canvas')
    canvas.width = 1920;
    canvas.height = 1080;

    var ctx = canvas.getContext('2d')

    initial();
    function initial() {
        let bgImg = new Image();
        bgImg.onload = drawBgImg;
        bgImg.src = 'https://media.istockphoto.com/id/1146517111/photo/taj-mahal-mausoleum-in-agra.jpg?s=612x612&w=0&k=20&c=vcIjhwUrNyjoKbGbAQ5sOcEzDUgOfCsm9ySmJ8gNeRk=';

    }

    function drawBgImg() {
        ctx.drawImage(this, 0, 0, 60, 60);
        drawSquare();
    }
    
    function drawSquare(){
        ctx.fillStyle = 'red';
        ctx.rect(10, 10, 100, 100);
        ctx.fill();
    }
</script>

</html>