关于javascript:CreateJs Canvas调整位图大小

CreateJs Canvas resize Bitmap

我目前正在使用createJS canvas。 我将一个具有预定义大小的图像放入Json文件,并在" mouseout"和" mouseover"上链接到eventListener的框。

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

图片的位图:

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

然后我画我的盒子(矩形):

1
2
3
4
5
6
7
8
9
10
11
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);

我的鼠标事件:

1
2
3
4
5
6
7
8
9
10
11
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();
});

因此,它正在工作,但是我在画布/图像尺寸方面遇到一些困难。

  • 如果我没有为画布HTML设置任何宽度/高度,则会导致
    300 * 150画布,但图像未调整大小,因此仅显示
    真实图像的一小部分。
  • 如果我在画布html中设置宽度和高度(实际大小为1700 * 1133),则图像仅显示842 * 561,并且发生了画布。
  • 我尝试了在JavaScript中设置DIV宽度和高度的其他解决方案
  • 但没有任何东西使我能够正确设置我的图像并做出响应,以使矩形的大小适应图像的屏幕大小。


    为了将画布动态调整为图像的确切大小,可以执行以下操作:

    1
    2
    3
    4
    5
    //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;

    如果屏幕上元素更多,并且总大小大于图像本身,则可以将屏幕上的所有内容添加到容器中,然后缩放容器本身以使其完全适合画布,如下所示:

    1
    2
    3
    4
    5
    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;