Search code examples
javascriptcanvascreatejs

CreateJs Canvas resize Bitmap


I'm currently working with createJS canvas. I have an image with a predefined size into a Json file and boxes that are link to an eventListener on "mouseout" and "mouseover").

var stage = new createjs.Stage("testCanvas");
createjs.Touch.enable(stage);
stage.enableMouseOver(10);

Bitmap for the image:

var image = new Image();
image.onload = function () {
  var img = new createjs.Bitmap(event.target);
  stage.addChild(img);

then i draw my boxes (rectangles):

angular.forEach(..., function(value){
  var rectGreen = new createjs.Shape();
  rectGreen.graphics.beginFill("green")
    .drawRect(
       value.shapeDimension....,
       value.shapeDimension....,
       value.shapeDimension....,
       value.shapeDimension....
     );
     rectGreen.alpha = 0.01;
     stage.addChild(rectGreen);

my mouse events:

rectGreen.addEventListener("mouseover", function (event) {
  var target = event.target;
  target.alpha = 0.35;
  stage.update();
});

rectGreen.addEventListener("mouseout", function (event) {
  var target = event.target;
  target.alpha = 0.01;
  stage.update();
});

So, it's working but I have some difficulties with the canvas/image size.

  1. If I don't set any width/heigth to the canvas Html, it results in a 300*150 canvas but the image is not resized so it displays only a slight piece of the real image.
  2. If i set width and height in the canvas html, (real size is 1700*1133), the image appears only 842*561 and the canvas takes place).
  3. I tried different solution with Setting DIV width and height in JavaScript

but nothing enabled me to set my image correctly, and responsive so that the size of my rectangles adpt to the screen size of the image.


Solution

  • In order to dynamically resize the Canvas to the exact size of the image, you can do this:

    //to get a variable reference to the canvas
    var canvas = document.getElementById("testCanvas");
    //supposing the Bitmap is the variable named 'img'
    canvas.width = img.image.width;
    canvas.height = img.image.height;
    

    If you have more elements on the screen and the total size is bigger than the image itself, you can add everything on the screen in a container, and then scale the container itself to fit the canvas perfectly, like this:

    var container = new createjs.Container();
    container.addChild(img, [your other rectangle elements here]);
    stage.addChild(container);
    //will downscale or upscale the container to fit the canvas
    container.scaleX = container.scaleY = canvas.width / img.image.width;