2

I have similar issue with layers as described here html5 - canvas element - Multiple layers

But, accepted answer doesn't work for me, as for layer1 I have rendered image (drawImage)

And second layer - layer2 (gradient) always under layer1.

Sample code:

    canvas = document.getElementById("layer1");
    ctx = canvas.getContext("2d");

    var img = new Image();
    img.src = "/img/img.png";
    img.onload = function() {
      ctx.drawImage(img, 0, 0);
    };

    canvas2 = document.getElementById("layer2");
    ctx2 = canvas.getContext("2d");

    var my_gradient = ctx2.createLinearGradient(0, 0, 0, 400);
    my_gradient.addColorStop(0, "black");
    my_gradient.addColorStop(1, "white");
    ctx2.fillStyle = my_gradient;
    ctx2.fillRect(0, 0, 500, 555);

HTML:

    <canvas id="layer1" width="1000" height="1000" style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
    <canvas id="layer2" width="1000" height="1000" style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
Community
  • 1
  • 1
Alex Ivasyuv
  • 8,585
  • 17
  • 72
  • 90

1 Answers1

3

You are setting ctx2 to layer1's context:

ctx2 = canvas.getContext("2d");

Of course, since the image loads asynchronously, the onload event fires after you've already drawn the gradient, and it gets drawn on the same canvas.

Matthew Crumley
  • 101,441
  • 24
  • 103
  • 129