Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

canvas - How to generate an Image from imageData in javascript?

I would like to know if there is any way to create a new Image from imageData, which was previously obtained from a canvas element?

I've searched for a solution, but they all seem to be drawing the result to a canvas. So basically I need a way to convert an ImageData object to Image directly, if its possible.

question from:https://stackoverflow.com/questions/13416800/how-to-generate-an-image-from-imagedata-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use toDataURL method in Canvas. It makes a image data as Data URI.

var canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
var ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 100, 100);

var img = document.createElement("img");
img.src = canvas.toDataURL("image/png");
document.body.appendChild(img);

If you want to know user's browser supports Data URI Scheme, You can use this function.

function useSafeDataURI(success, fail) {
    var img = document.createElement("img");

    img.onerror = function () {
        fail();
    };
    img.onload = function () {
        success();
    };

    img.src = "data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="; // insert a dot image contains 1px.
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...