Search code examples
javascriptkineticjs

KineticJS creating a canvas


I am new to both JavaScript/Canvas and KineticJS.

I know that it is possible to create a canvas and a stage like this -

    <div id="container"></div>
    <script src="http://www.html5canvastutorials.com/libraries/kinetic-v4.3.0-beta2.js"></script>
    <script>
      var stage = new Kinetic.Stage({
        container: 'container',
        width: 578,
        height: 200
      });
    </script>

But I was wondering if I already have a canvas, how will I create a stage out of it then? So something like this...

<canvas id="myCanvas"></canvas>
<script src="http://www.html5canvastutorials.com/libraries/kinetic-v4.3.0-beta2.js"></script>
<script>
    //How do I create a Kinetic.stage of the #myCanvas?
</script>

Solution

  • How about this:

    Create a new stage.

    Create a new layer.

    Create a new Image the same size as the stage.

    Set the Image's image source to myCanvas.

    Note: I didn't test the following code, but it should work +/- tweaks.

    var myCanvasImg=new Kinetic.Image({
          x: 0,
          y: 0,
          image: document.getElementById("myCanvas").getContext("2d").toImageURL(),
          width: stage.getWidth(),
          height: stage.getHeight()
        });
    

    Add the Image to the Layer and add the Layer to the Stage.

    Bang...New stage with myCanvas contents!