Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas drawImage using data URL

I'll start with the script:


  function saveInstance() {
   _savedInstance = document.getElementById('canvasID').toDataURL();
  }
  function restoreInstance() {
   ctx.drawImage(_savedInstance,0,0);
  }

The purpose is to save an instance of the canvas and re-apply it later [Similar to how ctx.save() saves the style and transformations].

However, I got the error that says incompatible types (Uncaught Error: TYPE_MISMATCH_ERR: DOM Exception 17). Is there any canvas method that will allow me to use the data URL string to re-draw the instance?

**If there's a better way to implement this save/restore idea I have, that'd also be much appreciated.

-Firstmate

like image 787
Firstmate Avatar asked Jul 31 '10 21:07

Firstmate


People also ask

How to draw image from data URL?

src = strDataURI; The drawImage() method draws an image, canvas, or video onto the canvas. The drawImage() method can also draw parts of an image, and/or increase/reduce the image size.

How do I use an image URL in canvas?

To get the image data URL of the canvas, we can use the toDataURL() method of the canvas object which converts the canvas drawing into a 64 bit encoded PNG URL. If you'd like for the image data URL to be in the jpeg format, you can pass image/jpeg as the first argument in the toDataURL() method.

How to load img in canvas?

Importing images into a canvas is basically a two step process: Get a reference to an HTMLImageElement object or to another canvas element as a source. It is also possible to use images by providing a URL. Draw the image on the canvas using the drawImage() function.


1 Answers

Yes, you can create an image element with its source as _savedInstance and then draw it to the canvas.

var img = new Image();
img.src = _savedInstance;
ctx.drawImage(img,0,0);
like image 108
pixl coder Avatar answered Sep 28 '22 14:09

pixl coder