我正在使用 WebGL 渲染图像并将其放在 Canvas 上。我想知道是否可以在该 Canvas 上放置一个 SVG 元素?
我实际上可以手动移动我在 Canvas 上绘制的矢量图像。所以我想应该有办法做到这一点。
最佳答案
与将任意两个元素放在彼此之上一样吗?使用 position:relative;
或 position:absolute;
给他们两个 parent 。将第二个(或两者)设置为 position:absolute;左:0;顶部:0; 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: 0;
top: 0;
z-index: 2;
width: 300px;
" />
</div>
例子:
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
function rand(r) {
return Math.random() * r | 0;
}
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: 0;
top: 0;
z-index: 2;
width: 300px;
" />
</div>
这似乎已经有人回答了,但方式相反here
关于html - 我可以将 svg 图像/元素放在 Canvas 元素之上吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24041111/