1

I have a canvas element

var canvas; // some canvas

which contains an image.

Is it possible to init a KineticJS Image from a canvas element? If not how would I get the KineticJS image from a canvas the fastest way?

Michael
  • 32,527
  • 49
  • 210
  • 370

1 Answers1

2

Sure!

You can use the canvas element as a source for a KineticJS.Image:

var canvas=document.getElementById("myCanvas");  // or createElement

...  // do stuff on the canvas element

var image1 = new Kinetic.Image({
    x:40,
    y:40,
    image:canvas,
});
layer.add(image1);
layer.draw();
markE
  • 102,905
  • 11
  • 164
  • 176
  • Can I switch the image from a KineticJS Image after it has created? This can be used to keep the Image properties but change the image itself? – Michael Apr 17 '14 at 19:00
  • I'm not really sure what your follow-on comment is asking :-\ The Kinetic.Image will update to reflect any new drawings on the Canvas element. The opposite is not true. If you rotate or scale the Kinetic.Image then the Canvas element remains unrotated and unscaled. Good luck with your project! – markE Apr 17 '14 at 19:22
  • My question was: Can I chnage the image resource, i.e., assign a new image to the KineticJS image? – Michael Apr 17 '14 at 19:33
  • This question is related may be you have a solution for this too? http://stackoverflow.com/questions/23141596/kineticjs-how-do-i-downsize-a-png-jpg-image-in-kineticjs-maintaining-high-quali – Michael Apr 17 '14 at 19:36
  • 1
    Sure, you can change the Kinetic.Image source with myImage.image(newImageObject); Note: newImageObject must be (1) an html img element (2) an in-memory image object: var newImageObject=new Image(), or (3) a canvas element. I'll take a look at the question in your link. – markE Apr 17 '14 at 19:42
  • the docs say that there is only a setImage(image) method which accepts an ImageObject. Are you sure there is a image(canvas) method? – Michael Apr 17 '14 at 21:54
  • 1
    Oops, sorry! It should be `myImage.setImage()` not myImage.image(). You can supply any of the 3 types of image to setImage. – markE Apr 17 '14 at 21:58
  • if it is a canvas I think it must be attached to the DOM is this right? – Michael Apr 17 '14 at 23:00
  • I still get errors using an off screen canvas do you have an example for that? – Michael Apr 17 '14 at 23:09