-2

I'm trying to draw some stuff over loaded image. However, for some reason canvas appears below the image not on top. I'm doing it as follows:

I have the following container:

<div id="container">
    <img src="{{url_for('static', filename='nature.jpg')}}" id="target" style="zIndex=1">
</div>>

And the I'm trying to add canvas as follows:

  window.onload = function() {
    var img = document.getElementById('target');
    var width = img.naturalWidth;
    var height = img.naturalHeight;

    var canvas = document.createElement('canvas'); //Create a canvas element
    //Set canvas width/height
    canvas.style.width=width;
    canvas.id = 'mycanvas';
    canvas.style.height=height;
    //Set canvas drawing area width/height
    canvas.width = width;
    canvas.height = height;
    //Position canvas
    canvas.style.position='absolute';
    canvas.style.left=0;
    canvas.style.top=0;
    canvas.style.zIndex=100000;
    canvas.style.pointerEvents='none'; //Make sure you can click 'through' the canvas
    $('#container').append(canvas);
}

However, canvas appears below the image rather than on top of it. What am I doing wrong?

thanks

drsealks
  • 2,282
  • 1
  • 17
  • 34

1 Answers1

1

You've used the wrong syntax for the inline style style="zIndex=1", it should be style="z-index: 1", still, for z-index to work its element need a position other than static

In this case, since the img has no position, you can actually drop the z-index all together, as the canvas has a position, position: absolute, and will be layered on top of the image because of that alone.

For the canvas to be positioned relative to the container, the container need a position, i.e. position: relative

Asons
  • 84,923
  • 12
  • 110
  • 165