views:

166

answers:

1

I have similar issue with layers as described here http://stackoverflow.com/questions/3008635/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>
+1  A: 

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
Yes, you right. It works now. But it's strange, as layer2 has z-index more over.Any way, it works now, thanks!
Alex Ivasyuv