我可以将svg图像/元素放在画布元素的顶部吗?

Kur*_*Liu 2 css html5 vector snap.svg

我正在使用WebGL渲染一些图像并将它们放在画布上.我想知道是否可以在画布上放置一个svg元素?

我实际上可以手动移动我在画布上绘制的矢量图像.所以我想应该有办法做到这一点.

gma*_*man 10

你把任何两个元素放在一起是一样的吗?给他们两个父母position:relative;或两个或position:absolute;.将第二个(或两个)设置为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>
Run Code Online (Sandbox Code Playgroud)

例:

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();
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

这似乎是它已经被回答,但以相反的方式在这里