-->

Convert HTML5 canvas to IMG element

2019-01-17 13:32发布

问题:

I would like to resize, stretch an HTML5 canvas in someway that the canvas act like an IMG element: set width-height by pixel, percent...

I wonder if is there any way to convert/export an HTML5 canvas to an IMG element, or someway that can make this possible directly in canvas.

I have researched on Google, but it seem like no one on the internet have done this before, or maybe I just cannot figure out...

I'm using KineticJS library, for details.

Please help me! Thank you so much! And sorry for my bad english...

回答1:

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