K
K
kos94ok2021-01-10 19:07:21
JavaScript
kos94ok, 2021-01-10 19:07:21

Why is canvas rendering an empty image?

Hello! There is such a code

var c=document.querySelector("canvas");

    var ctx=c.getContext("2d");
    var imageObj1 = new Image();
    imageObj1.src = "background.jpg";

    var imageObj2 = new Image();

    c.width = imageObj1.width;
    c.height = imageObj1.height;

    imageObj1.onload = function() {

       ctx.globalAlpha = 1;
       ctx.drawImage(imageObj1, 0, 0, imageObj1.width, imageObj1.height);
       imageObj2.src = "foreground.jpg";
       imageObj2.onload = function() {
          ctx.drawImage(imageObj2, (imageObj1.width / 2) - (imageObj2.width / 2), (imageObj1.height / 2) - (imageObj2.height / 2), imageObj2.width, imageObj2.height);
          var img = c.toDataURL("image/png");
          $('html').append(img)
          document.write('<img src="' + img + '" style="width: 100%; max-width: 500px;"/>');
       }
    };

In this code, I am trying to overlay two images on top of each other. Everything works fine in the Safari browser. In browsers such as Google Chrome, Yandex, an empty image is rendered. Why?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2021-01-10
@Seasle

- c.width = imageObj1.width;
- c.height = imageObj1.height;

imageObj1.onload = function() {
+   c.width = imageObj1.width;
+   c.height = imageObj1.height;
    ctx.globalAlpha = 1;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question