Can I place a svg image/element on top a canvas element?

Kurt Liu picture Kurt Liu · Jun 4, 2014 · Viewed 9.7k times · Source

I am using WebGL to rendering some image and put them on a canvas. I am wondering will it be possible to put a svg element on that canvas?

I actually can move the vector image I draw on top of canvas manually. So I suppose there should be a way to do that.

Answer

gman picture gman · Jun 5, 2014

Same as you place any two elements on top of each other? Give them both a parent with either position:relative; or position:absolute;. Set the second one (or both) to position:absolute; left: 0px; top:0px; z-index: 2;

<div style="position: relative;">
  <canvas id="c" width="300" height="300"></canvas>
  <img src="http://s.cdpn.io/3/kiwi.svg" 
       style="position: absolute; 
              left: 0px; 
              top:0px;
              z-index: 2;
              width: 300px;
       " />
</div>

Example:

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

function rand(r) {
   return Math.floor(Math.random() * r);
}

function draw() {
  ctx.fillStyle ="rgb(" + 
                rand(256) + "," +
                rand(256) + "," +
                rand(256) + ")";
  
  ctx.fillRect(
      -150 + rand(canvas.width), 
      -150 + rand(canvas.height),
      rand(300),
      rand(300));
   requestAnimationFrame(draw);
}
draw();
<div style="position: relative;">
      <canvas id="c" width="300" height="300"></canvas>
      <img src="http://s.cdpn.io/3/kiwi.svg" 
           style="position: absolute; 
                  left: 0px; 
                  top:0px;
                  z-index: 2;
                  width: 300px;
           " />
    </div>

This seems like it's already been answered but in the opposite way here