Html 将 HTML5 画布转换为 IMG 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18008473/
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
Convert HTML5 canvas to IMG element
提问by TrungDQ
I would like to resize, stretch an HTML5 canvas in a way that the canvas act like an IMG element: set width-height by pixel, percent...
我想调整大小,以画布像 IMG 元素一样的方式拉伸 HTML5 画布:按像素设置宽高,百分比...
I wonder if is there any way to convert/export an HTML5 canvas to an IMG element, or any way that can make this possible directly on the canvas.
我想知道是否有任何方法可以将 HTML5 画布转换/导出为 IMG 元素,或者任何可以直接在画布上实现这一点的方法。
I'm using KineticJS library, for details.
我正在使用 KineticJS 库以获取详细信息。
Please help!
请帮忙!
回答by federico-t
First, give your canvas an id (e.g. example
). Then, using plain JavaScript you can create an image based on that canvas and style it:
首先,给你的画布一个 id(例如example
)。然后,使用纯 JavaScript,您可以基于该画布创建图像并为其设置样式:
var canvas = document.getElementById('example'),
dataUrl = canvas.toDataURL(),
imageFoo = document.createElement('img');
imageFoo.src = dataUrl;
// Style your image here
imageFoo.style.width = '100px';
imageFoo.style.height = '100px';
// After you are done styling it, append it to the BODY element
document.body.appendChild(imageFoo);