1

我将 Paper.js 用于一些画布绘图。我正在尝试根据画布大小调整光栅的大小和位置,但我的代码无法正常工作。

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 有点滞后。但我不知道如何克服这个问题。

4

1 回答 1

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 ...
}
于 2013-07-31T13:50:53.610 回答