Jump to content

Is there a way to create an Image from canvas.getImageData?


rich
 Share

Recommended Posts

Warning: Question posted without any form of testing by me, in the hope someone has already done it :)

 

You can get all the pixel data from a canvas easily with getImageData.

 

But is there any way to turn that data back into something you can use in a normal Image() object? (which is then maybe added to the DOM).

Link to comment
Share on other sites

You can do that without getImageData(), with a data URL:

img.src = canvas.toDataURL();

On some (but not all) browsers, assigning a value to img.src doesn't have an immediate effect though, it may happen on the next idle cycle. Just mentioning it because that's caught me out a couple of times.

Link to comment
Share on other sites

In my experience it does, but again it may or may not happen immediately depending on the browser. So I'd listen for the load event first, then set the src, just in case your browser does trigger the event right away (if I remember correctly firefox does this).

Link to comment
Share on other sites

In my experience it does, but again it may or may not happen immediately depending on the browser. So I'd listen for the load event first, then set the src, just in case your browser does trigger the event right away (if I remember correctly firefox does this).

I can't remember where I read that but I think that the specs say : src attribute have to be set before the onload attribute so the event can fire correctly.

 

Link to comment
Share on other sites

FYI canvas.toDataURL() generates a PNG by default, but you can pass a MIME type as argument, e.g. "image/png" or "image/jpeg" in which case some browsers might take an optional second argument between 0 and 1 for the quality setting of the JPEG.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...