如何将 HTML 元素转换为画布元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2732488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert an HTML element to a canvas element?
提问by davemyron
It would be incredibly useful to be able to temporarily convert a regular element into a canvas
. For example, say I have a styled div
that I want to flip. I want to dynamically create a canvas, "render" the HTMLElement
into the canvas, hide the original element and animate the canvas.
能够临时将常规元素转换为canvas
. 例如,假设我有一个div
想要翻转的样式。我想动态创建一个画布,将其“渲染”HTMLElement
到画布中,隐藏原始元素并为画布设置动画。
Can it be done?
可以做到吗?
采纳答案by bobince
Sorry, the browser won't render HTML into a canvas.
抱歉,浏览器不会将 HTML 呈现到画布中。
It would be a potential security risk if you could, as HTML can include content (in particular images and iframes) from third-party sites. If canvas
could turn HTML content into an image and then you read the image data, you could potentially extract privileged content from other sites.
如果可以,这将是一个潜在的安全风险,因为 HTML 可以包含来自第三方站点的内容(特别是图像和 iframe)。如果canvas
可以将 HTML 内容转换为图像,然后您读取图像数据,您就有可能从其他站点提取特权内容。
To get a canvas from HTML, you'd have to basically write your own HTML renderer from scratch using drawImage
and fillText
, which is a potentially huge task. There's one such attempt herebut it's a bit dodgy and a long way from complete. (It even attempts to parse the HTML/CSS from scratch, which I think is crazy! It'd be easier to start from a real DOM node with styles applied, and read the styling using getComputedStyle
and relative positions of parts of it using offsetTop
et al.)
要从 HTML 获取画布,您基本上必须使用drawImage
and从头开始编写自己的 HTML 渲染器fillText
,这可能是一项艰巨的任务。这里有一个这样的尝试,但它有点狡猾,离完成还有很长的路要走。(它甚至试图从头开始解析 HTML/CSS,我认为这很疯狂!从应用了样式的真实 DOM 节点开始会更容易,并getComputedStyle
使用offsetTop
et al读取样式使用和部分的相对位置.)
回答by Aristos
There is a library that try to do what you say.
有一个图书馆试图按照你说的去做。
See this examples and get the code
查看此示例并获取代码
http://hertzen.com/experiments/jsfeedback/
http://hertzen.com/experiments/jsfeedback/
http://html2canvas.hertzen.com/
http://html2canvas.hertzen.com/
Reads the DOM, from the html and render it to a canvas, fail on some, but in general works.
从 html 中读取 DOM 并将其渲染到画布上,在某些情况下会失败,但通常可以正常工作。
回答by natevw
Take a look at this tutorial on MDN: https://developer.mozilla.org/en/HTML/Canvas/Drawing_DOM_objects_into_a_canvas (archived)
在MDN上查看本教程:https: //developer.mozilla.org/en/HTML/Canvas/Drawing_DOM_objects_into_a_canvas(已存档)
Alternate Link (2019) : https://reference.codeproject.com/book/dom/canvas_api/drawing_dom_objects_into_a_canvas
备用链接(2019):https: //reference.codeproject.com/book/dom/canvas_api/drawing_dom_objects_into_a_canvas
It uses a temporary SVG imageto include the HTMLcontent as a "foreign element", then renders said SVG image into a canvas element. There are significant restrictions on what you can include in an SVG image in this way, however. (See the "Security" section for details.)
它使用临时SVG 图像将HTML内容包含为“外部元素”,然后将所述 SVG 图像呈现到画布元素中。但是,以这种方式可以在 SVG 图像中包含的内容存在重大限制。(有关详细信息,请参阅“安全性”部分。)
回答by cburgmer
Building on top of the Mozdev post that natevw references I've started a small project to render HTML to canvas in Firefox, Chrome & Safari. So for example you can simply do:
在 natevw 引用的 Mozdev 帖子的基础上,我启动了一个小项目,在 Firefox、Chrome 和 Safari 中将 HTML 呈现到画布上。例如,您可以简单地执行以下操作:
rasterizeHTML.drawHTML('<span class="color: green">This is HTML</span>'
+ '<img src="local_img.png"/>', canvas);
Source code and a more extensive example is here.
源代码和更广泛的示例在这里。
回答by tsayen
You can use dom-to-imagelibrary (I'm the maintainer).
Here's how you could approach your problem:
您可以使用dom-to-image库(我是维护者)。
以下是您解决问题的方法:
var parent = document.getElementById('my-node-parent');
var node = document.getElementById('my-node');
var canvas = document.createElement('canvas');
canvas.width = node.scrollWidth;
canvas.height = node.scrollHeight;
domtoimage.toPng(node).then(function (pngDataUrl) {
var img = new Image();
img.onload = function () {
var context = canvas.getContext('2d');
context.translate(canvas.width, 0);
context.scale(-1, 1);
context.drawImage(img, 0, 0);
parent.removeChild(node);
parent.appendChild(canvas);
};
img.src = pngDataUrl;
});
回答by Simon Sarris
No such thing, sorry.
没有这种事,抱歉。
Though the spec states:
尽管规范指出:
A future version of the 2D context API may provide a way to render fragments of documents, rendered using CSS, straight to the canvas.
2D 上下文 API 的未来版本可能会提供一种将使用 CSS 渲染的文档片段直接渲染到画布的方法。
Which may be as close as you'll get.
这可能与您会得到的一样接近。
A lot of people want a ctx.drawArbitraryHTML/Element
kind of deal but there's nothing built in like that.
很多人都希望达成ctx.drawArbitraryHTML/Element
某种交易,但没有任何内在的东西。
The only exception is Mozilla's exclusive drawWindow
, which draws a snapshot of the contents of a DOM window into the canvas. This feature is only available for code running with Chrome ("local only") privileges. It is not allowed in normal HTML pages. So you can use it for writing FireFox extensions like this one doesbut that's it.
唯一的例外是 Mozilla 独有的drawWindow
,它将 DOM 窗口内容的快照绘制到画布中。此功能仅适用于以 Chrome(“仅限本地”)权限运行的代码。在普通的 HTML 页面中是不允许的。所以你可以用它来编写 FireFox 扩展,就像这个一样,但就是这样。
回答by Jürgen Messing
You could spare yourself the transformations, you could use CSS3 Transitionsto flip <div>
's and <ol>
's and any HTML tag you want. Here are some demos with source code explain to see and learn: http://www.webdesignerwall.com/trends/47-amazing-css3-animation-demos/
你可以省去转换,你可以使用CSS3 Transitions来翻转<div>
's 和<ol>
's 以及任何你想要的 HTML 标签。以下是一些带有源代码解释的演示以供查看和学习:http: //www.webdesignerwall.com/trends/47-amazing-css3-animation-demos/
回答by olanod
The easiest solution to animate the DOM elements is using CSS transitions/animations but I think you already know that and you try to use canvas to do stuff CSS doesn't let you to do. What about CSS custom filters? you can transform your elements in any imaginable way if you know how to write shaders. Some other linkand don't forget to check the CSS filter lab.
Note: As you can probably imagine browser support is bad.
为 DOM 元素设置动画的最简单解决方案是使用 CSS 过渡/动画,但我认为您已经知道这一点,并且您尝试使用画布来做 CSS 不允许您做的事情。什么CSS自定义过滤器?如果您知道如何编写着色器,则可以以任何可以想象的方式转换元素。其他一些链接,不要忘记检查CSS filter lab。
注意:正如您可能想象的那样,浏览器支持很差。
回答by Luis Villadiego
the next code can be used in 2 modes, mode 1 save the html code to a image, mode 2 save the html code to a canvas.
接下来的代码可以在两种模式下使用,模式 1 将 html 代码保存到图像,模式 2 将 html 代码保存到画布。
this code work with the library: https://github.com/tsayen/dom-to-image
此代码与库一起使用:https: //github.com/tsayen/dom-to-image
*the "id_div" is the id of the element html that you want to transform.
*“id_div”是要转换的元素 html 的 id。
**the "canvas_out" is the id of the div that will contain the canvas so try this code. :
**“canvas_out”是包含画布的 div 的 id,所以试试这个代码。:
function Guardardiv(id_div){
var mode = 2 // default 1 (save to image), mode 2 = save to canvas
console.log("Process start");
var node = document.getElementById(id_div);
// get the div that will contain the canvas
var canvas_out = document.getElementById('canvas_out');
var canvas = document.createElement('canvas');
canvas.width = node.scrollWidth;
canvas.height = node.scrollHeight;
domtoimage.toPng(node).then(function (pngDataUrl) {
var img = new Image();
img.onload = function () {
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
};
if (mode == 1){ // save to image
downloadURI(pngDataUrl, "salida.png");
}else if (mode == 2){ // save to canvas
img.src = pngDataUrl;
canvas_out.appendChild(img);
}
console.log("Process finish");
});
}
so, if you want to save to image just add this function:
因此,如果您想保存到图像,只需添加此功能:
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
}
Example of use:
使用示例:
<html>
<head>
</script src="/dom-to-image.js"></script>
</head>
<body>
<div id="container">
All content that want to transform
</div>
<button onclick="Guardardiv('container');">Convert<button>
<!-- if use mode 2 -->
<div id="canvas_out"></div>
</html>
Comment if that work. Comenten si les sirvio :)
评论是否有效。评论 si les sirvio :)
回答by Seo Gregory
function convert() {
dom = document.getElementById('divname');
var script,
$this = this,
options = this.options,
runH2c = function(){
try {
var canvas = window.html2canvas([ document.getElementById('divname') ], {
onrendered: function( canvas ) {
window.open(canvas.toDataURL());
}
});
} catch( e ) {
$this.h2cDone = true;
log("Error in html2canvas: " + e.message);
}
};
if ( window.html2canvas === undefined && script === undefined ) {
} else {.
// html2canvas already loaded, just run it then
runH2c();
}
}