Question

I'm using Paper.js for some canvas drawings. I'm trying to resize and position an Raster depending on canvas size but my code doesn't works properly.

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);

when I load the page for the first time, I get this logs:

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

but after refreshing the page, everything works fine.

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

I think creating a new var for a Raster lags a bit at the first time. But i have no idea how to overcome this problem.

Was it helpful?

Solution

If you create a raster with a url as the input, you can use the onLoad handler to hold a function. In your case:

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 ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top