gpt4 book ai didi

javascript - 在 Canvas 上绘制背景图像

转载 作者:太空宇宙 更新时间:2023-11-04 04:42:20 24 4
gpt4 key购买 nike

我正在尝试将 dom 对象绘制到 Canvas 上,如下所示。

https://developer.mozilla.org/en-US/docs/HTML/Canvas/Drawing_DOM_objects_into_a_canvas

我有以下代码,背景图像似乎不起作用?我在这里做错了什么吗?或者有办法解决吗?

See Fiddle

    <canvas id="canvas" style="border:2px solid black;" width="400" height="300"></canvas>
<div style='background-color:red' class='test'><h1>Hello World</h1></div>
<div style='background-image:url(http://lorempixel.com/400/100/transport/)' class='test'><h1>Hello World</h1></div>


<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var data = "<svg xmlns='http://www.w3.org/2000/svg' width='500' height='500'>" +
"<foreignObject width='100%' height='100%'>" +
"<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:40px'>" +
"<div style='background-color:red' class='test'><p>Hello World</p></div>" +
"<div style='background-image:url(http://lorempixel.com/500/500/transport/)' class='test'><p>Hello World</p></div>" +
"</div>" +
"</foreignObject>" +
"</svg>";
var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
};
img.src = url;
</script>

最佳答案

SVG images aren't allowed to load any external resources, for example, even ones that appear to be from the same domain. Resources such as raster images (such as JPEG images) or s have to be inlined as data: URIs.

这是来自您链接的页面。这确认您不能使用背景图像,除非您将它们转换为 data URI。就其本身而言,这并不,您所要做的就是将图像复制到另一个 Canvas 并在其上使用toDataURL()。但是,您需要扫描输入以查找任何此类图像,并且它仍然只适用于相同域的资源。

关于javascript - 在 Canvas 上绘制背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15212729/

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