我正在尝试将 dom 对象绘制到画布上,如下所示。
https://developer.mozilla.org/en-US/docs/HTML/Canvas/Drawing_DOM_objects_into_a_canvas
我有下面的代码,它看起来好像背景图像不起作用?我在这里做错了吗?或者有没有办法解决它?
<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>