mouse coordinates offset after window resized

75 views
Skip to first unread message

El gyn

unread,
May 4, 2023, 10:45:59 AM5/4/23
to Paper.js
Hello,

With a fixed canvas size (fixed width and height attributes) somewhy the coordinates get messed up after resizing window (which zooms out the canvas). Is there a way to update the bounds?

For example, in Phaser there is the ScaleManager.updateBounds method that is called every time the browser fires a 'resize' or 'orientationchange' event. This will update the offset of the canvas element Phaser is rendering to, which is responsible for keeping input positions correct.

Is there any equivalent method with paper.js?

Thanks

Marlus Araujo

unread,
Aug 5, 2023, 2:09:38 PM8/5/23
to Paper.js
Hello there,

I don't know if this helps, but on my last project I used this technique:
  • create a wrapper div for canvas, that can change proportions via CSS (1:1, 16:9, 4:3)
  • on resize function, I get this proportion and change canvas size accordingly, with a desired resolution for canvas (1024px)
  • update view.viewSize and save viewCenter, which I use as a reference for all objects
  • also check for wrapper changes on every frame

let w:number, h:number;
const canvasWrapper = document.getElementById('app-canvas')
const canvas = document.getElementById('canvas') as HTMLCanvasElement
let viewCenter: paper.Point

window.onload = function() {
paper.setup(canvas)
paper.view.onResize = () => {
if(canvasWrapper){
w = canvasWrapper.offsetWidth
h = canvasWrapper.offsetHeight
const res = 1024;
let canvasW = w >= h ? res : w/h * res;
let canvasH = w >= h ? h/w * res : res;
canvasW = Math.round(canvasW)
canvasH = Math.round(canvasH)
viewCenter = new paper.Point(canvasW * 0.5, canvasH * 0.5)
paper.view.viewSize = new paper.Size(canvasW,canvasH);
paper.view.center = viewCenter
}
}

....


In this project, I change the wrapper size via CSS, like this:

#app-canvas.ratio-1-1 {
max-width: 90vh;
aspect-ratio: 1 / 1;
}

#app-canvas.ratio-16-9 {
max-width: calc(70vh * 16 / 9);
aspect-ratio: 16 / 9;
}

#app-canvas.ratio-4-3 {
max-width: calc(90vh * 4 / 3);
aspect-ratio: 4 / 3;
}

#app-canvas.ratio-3-4 {
max-height: 90vh;
aspect-ratio: 3 / 4;
}

#app-canvas.ratio-9-16 {
max-height: 90vh;
aspect-ratio: 9 / 16;
}


On everyframe, I check if the values changed:

if(paper.view.onResize && appCanvas && (w !== appCanvas.offsetWidth || h !== appCanvas.offsetHeight)){
paper.view.onResize()
}

Hope this can help you!

Best,

Marlus
Reply all
Reply to author
Forward
0 new messages