Search code examples
javascriptcanvaskineticjs

KineticsJs auto resize canvas


My autoresize canvas not works with kineticjs, the console say me that canvas.width and canvas.height is not defined.

Any people could help me.

Thank you .

Put the function and the call down.

function resize() {
    console.log("ddddddddddddd");
//stage.setWidth((window.innerWidth / 100) * 80);

    var canvas = document.getElementById('Contenedor');
    console.log(canvas, canvas.height, canvas.width);
    if(window.innerWidth < 1280){
       var canvasRatio = canvas.height / canvas.width;
       console.log(canvasRatio);
       var windowRatio = window.innerHeight / window.innerWidth;
       console.log(windowRatio);
       var width;
       var height;

       if (windowRatio < canvasRatio) {
           height = window.innerHeight;
           width = height / canvasRatio;
       } else {
           width = window.innerWidth;
           height = width * canvasRatio;
       }

       canvas.style.width = (parseFloat(width)*0.75) + 'px';
       canvas.style.height = (parseFloat(height)*0.75) + 'px';
   }else{
    canvas.style.width=987+'px';
    canvas.style.height=544+'px';
   }    
};
window.addEventListener('resize', resize, false);

Solution

  • What you can do is set the height of the canvas with respect to the width. And use stage.setScale() and stage.setSize() to dynamically change the size of the stage

    function resize() {
            var canvasWidthRatio = 0.6;        // canvas width to viewport width ratio
            var viewPortWidth = window.innerWidth;
            var canvasWidth = viewPortWidth * canvasWidthRatio;
            var canvasHeight = canvasWidth * 0.6,
                scale = stage.getScale(),
                stageWidth = stage.getWidth(),
                stageHeight = stage.getHeight(),
                scaleFactor = Math.min(canvasWidth / stageWidth, canvasHeight / stageHeight),
                newScale = scale * scaleFactor;
            stage.setScale(newScale);
            stage.setSize(canvasWidth, canvasHeight);
            stage.draw();
    }
    window.addEventListener('resize', resize, false);