如何构建Raster并调整大小?

时间:2013-07-31 09:27:45

标签: javascript paperjs

我正在使用Paper.js绘制一些画布。我正在尝试根据画布大小调整大小并定位Raster,但我的代码无法正常工作。

var canvas = document.getElementById('canvas');
paper.setup(canvas);
var pitch = new paper.Raster('{{ STATIC_URL }}images/pitch.png');

var width = paper.view.size.width;
var height = paper.view.size.height;
console.log("screen dimensions: " + width + " " + height);
var midPoint = [width/2,height/2];
var paddingLeft = width/40;
var scale = (height/pitch.height)*(90/100);
console.log("scale: " + scale);
pitch.scale(scale);
console.log("pitch dimensions: " + pitch.height + " " + pitch.width);
pitch.position = [midPoint[0] + paddingLeft - (width-pitch.width*scale)/2 , midPoint[1]];
console.log("pitch position: " + pitch.position);

当我第一次加载页面时,我得到了这个日志:

screen dimensions: 472.5 340 
scale: Infinity 
pitch dimensions: 0 0 
pitch position: { x: NaN, y: NaN } 

但刷新页面后,一切正常。

screen dimensions: 472.5 340 
scale: 0.6120000000000001
pitch dimensions: 500 759
pitch position: { x: 244.0665, y: 170 }

我认为为Raster创建一个新的var在第一次有点滞后。但我不知道如何克服这个问题。

1 个答案:

答案 0 :(得分:0)

如果创建带有url作为输入的栅格,则可以使用onLoad处理程序来保存函数。在你的情况下:

var canvas = document.getElementById('canvas');
paper.setup(canvas);
var pitch = new paper.Raster('{{ STATIC_URL }}images/pitch.png');

pitch.onLoad = function () {
  var width = paper.view.size.width; 
  etc ...
}