将 HTML5 画布转换为 IMG 元素

我想调整 HTML5 画布的大小、拉伸 HTML5 画布,使画布像 IMG 元素一样:按像素设置宽度-高度、百分比...

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...

我想知道是否有任何方法可以将 HTML5 画布转换/导出为 IMG 元素,或者任何可以直接在画布上实现这一点的方法.

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.

我正在使用 KineticJS 库,了解详情.

I'm using KineticJS library, for details.

请帮忙!

推荐答案

首先,给你的画布一个 id(例如 example).然后,使用纯 JavaScript,您可以基于该画布创建图像并为其设置样式:

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:

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);

相关文章