gpt4 book ai didi

html5-canvas - 如何在 canvas 元素中使用 html 内容

转载 作者:行者123 更新时间:2023-12-02 00:04:50 25 4
gpt4 key购买 nike

谁能告诉我如何将我的 html 内容放在 Canvas 上。如果我们可以做到这一点,这些元素的属性和事件是否有效,而且我在 Canvas 上绘制了动画。

最佳答案

来自 this article on MDN :

You can't just draw HTML into a canvas. Instead, you need to use an SVG image containing the content you want to render. To draw HTML content, you'd use a element containing the HTML, then draw that SVG image into your canvas.

它建议您按照以下步骤操作:

The only really tricky thing here—and that's probably an overstatement—is creating the SVG for your image. All you need to do is create a string containing the XML for the SVG and construct a Blob with the following parts.

  1. The MIME media type of the blob should be "image/svg+xml".
  2. The element.
  3. Inside that, the element.
  4. The (well-formed) HTML itself, nested inside the .

By using a object URL as described above, we can inline our HTML instead of having to load it from an external source. You can, of course, use an external source if you prefer, as long as the origin is the same as the originating document.

提供了以下示例(您可以在 this blog by Robert O'Callahan 中查看更多相关信息):

演示

const ctx = document.getElementById("canvas").getContext("2d");
const data = `
<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'>
<foreignObject width='100%' height='100%'>
<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:40px'>
<em>I</em> like <span style='color:white; text-shadow:0 0 2px blue;'>CANVAS</span>
</div>
</foreignObject>
</svg>
`;
const img = new Image();
const svg = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
const url = URL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
URL.revokeObjectURL(url);
};
img.src = url;
<canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas>

这个例子导致这个 HTML 被渲染到 Canvas 上,如下所示:

HTML to canvas snapshot

Will the properties and events of those elements works or not ?

不,绘制到 Canvas 上的所有内容都被遗忘为被动像素 - 它们只是一张图像。

您需要提供您自己提供的自定义逻辑,以便处理诸如点击、对象、事件等任何事情。逻辑需要定义区域、对象和任何其他内容。

关于html5-canvas - 如何在 canvas 元素中使用 html 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19021237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com