jqueryeaseljs

change stage size to fit window resize without scaling


I am adopting easeljs from raw canvas programming, one feature that has me stuck is how to resize the stage when the browser window resized.

I just listen to the resize event of the window and change the canvas size accordingly, I have simplified the example to cover the complete window.

  // resize the canvas to fill browser window dynamically
  function resizeCanvas() {
    $('#canvas').width($(window).innerWidth());
    $('#canvas').height($(window).innerHeight());
    renderBoard();
  }
  resizeCanvas();
  $(window).on('resize', resizeCanvas);

and for this example, my renderBoard() function contains

  function renderBoard() {
    let centerCircle = new createjs.Shape();
    centerCircle.graphics.beginStroke("red")
      .drawCircle(canvas.clientWidth / 2, canvas.clientHeight / 2, 4);
    let playingRect = new createjs.Shape();
    playingRect.graphics.beginFill("green")
      .rect(10,10, canvas.clientWidth-20,canvas.clientHeight-20);

    stage.addChild(playingRect,centerCircle);
    stage.setChildIndex(playingRect, 0);
    stage.update();
  }

my new render distorts and scales with the canvas, which I don't want. What is the correct way to resize the stage without scaling its contents?


Solution

  • I found the culprit. jQuery

    jQuery.width() (and jQuery.height()) implementation uses CSS styling to change the width of the element selected, which is not correctly interpreted by easeljs.

    The solution was simply to direct change of the width of the element without using jQuery

    change the line

    $('#canvas').width($(window).width());
    

    to be

    $('canvas').get(0).width=$(window).width();