Search code examples
javascriptcsskineticjs

Resizing a stage with css height and width


I want to work with kineticJS on a display area that is defined (height and width) in two ways :

-In my javascript, I want to have arbitrary dimensions to work with, place items, etc. -In my CSS, I want other dimensions, independantly of the JS one, representing the real display.

There are several advantages to this : JS dimensions can be smaller than the real display, to make computing lighter ; or CSS dimensions can be adapted to the user screen dimensions easely, without impact on the scripting part...

This is easy to do in vanilla JS, using attributes height and width of the canvas for the JS dimensions, and CSS height and width for the display dimensions.

HTML:

<canvas height="10" width="10" id="c"></canvas>

CSS:

#c {
        height:400px;
        width:400px;
    }

Example : http://jsfiddle.net/5fW8f/2/

But with KineticJS, I'm curently unable to do the same thing. When I do this width the container, the container itself is sizing as well, but Stage is not (using dimensions of the stage of or the container).

HTML :

<div height="100" width="100" id="c"></div>

Same CSS.

Example : http://jsfiddle.net/46JCa/

So, is there a way to do it with KineticJS ?


Solution

  • I think what you're looking for is

    stage.setScale(scale);
    

    Where scale is the ratio you want to scale everything by. Thus you need only calculate it once, set it, and you're done (unless you're using multiple stages; then you'd want to set all of them).

    For an example, see http://www.html5canvastutorials.com/labs/html5-canvas-multi-touch-scale-stage-with-kineticjs/

    It's fast and I use this trick frequently. You can actually scale any object independently, if you want, or when drawing directly on the canvas.