Matt Martinez
Matt Martinez

Reputation: 61

Position svg element higher on top of another element

I know this has been answered in other places because I've looked, but nothing I can find seems to do the trick, sorry for posting a question that's been asked before.

I just need to append a transparent svg element exactly over my canvas element, but whenever I append, the svg goes under the canvas, no matter what I try with positioning and z-index.

Thanks in advance for the help and sorry for my newb question, I'm new to coding. Here's the code I think is appropriate:

here's the css:

canvas {
    position: absolute;
    top: 0px;
    left: 0px;
}

and the javascript for canvas:

var width = screen.width;
var height= screen.height;
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;

and finally my javascript for creating and appending the element:

function getCanvas(canvas) {
    var top = canvas.css('top');
    var left = canvas.css('left');
    var canvaswidth = canvas.width();
    var canvasheight = canvas.height();
    var svg = $('<svg>Hey</svg>').attr({
        'xmlns': 'http://www.w3.org/2000/svg',
        'width': canvaswidth,
        'height': canvasheight,
        'top': top,
        'left': left,
        'position': 'absolute',
        'opacity': 1,
        'id': 'svg'
    });
    svg.css({backgroundColor: 'black', 'z-index': 10});
    svg.insertAfter(canvas);
}

Thanks!

Upvotes: 0

Views: 1423

Answers (1)

tzi
tzi

Reputation: 9459

You doesn't need to have a z-index at all, since you svg is after your canvas element.

The problem comes from that the property position is not set the right way. It is set as an attribute instead of as a style property.

canvas = $('#canvas');
var svg = $('<svg><text x="50" y="50">Hey</text></svg>').attr({
  xmlns: 'http://www.w3.org/2000/svg',
  id: 'svg'
}).css({
  position: 'absolute',
  top: canvas.css('top'),
  left: canvas.css('left'),
  width: canvas.width(),
  height: canvas.height(),
  opacity: 1,
});
svg.insertAfter(canvas);
canvas {
    position: absolute;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<canvas id="canvas"></canvas>

Upvotes: 1

Related Questions