问题
In this example:
var canvas = document.getElementById("testCanvas");
var stage = new createjs.Stage(canvas);
function drawRectangle(){
var rect = new createjs.Shape();
rect.graphics.beginFill("#000").drawRect(10, 10, 100, 100);
stage.addChild(rect);
}
function drawShapes(){
drawRectangle();
stage.update();
}
drawShapes();
// Why does this call log null?
console.log(stage.getBounds());
<script src="https://cdnjs.cloudflare.com/ajax/libs/EaselJS/0.8.0/easeljs.min.js"></script>
<canvas id="testCanvas" width="600" height="150"></canvas>
stage.getBounds();
is returning null. Why does it return null? According to the docs, it's supposed to return a rectangle object representing the dimensions of the bounding box of the stage.
If this usage is incorrect, what is the correct usage to get the dimensions of the object?
回答1:
It looks like the stage object can't calculate their own bounds.
In the same getBounds()
documentation it appears the following:
Not all display objects can calculate their own bounds (ex. Shape). For these objects, you can use setBounds so that they are included when calculating Container bounds.
If it's the case, as the documentation says, you can use the setBounds()
method (documentation) to set manually the bounds of the object:
setBounds(x,y,width,height)
In the case of your code:
stage.setBounds(0,0,600,150); // (0,0), at the same size of the canvas
来源:https://stackoverflow.com/questions/45484931/why-does-easeljs-stage-getbounds-return-null