html - 我可以将 svg 图像/元素放在 Canvas 元素之上吗?

标签 html svg layout html5-canvas

我正在使用 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/

相关文章:

css - 添加了品牌形象SVG额外的透明空间

reactjs - React Native SVG - 设置 SVG 宽度和高度会导致图标被截断

具有不同行高的 ListView 中的 Android RelativeLayout fill_parent 意外行为

html - 将悬停更改为触摸

javascript - 如何像 Github 那样制作 52 周的参与条形图?

c# - 将对话框置于窗口之上,但不置于所有内容之上

php - 如何防止 CSS 中的 Div 换行?

html - css div 100% 高度问题

javascript - 加载时显示输入文件对话框?

html - 同一页面上 ID 的 anchor 链接不起作用