I'm trying to get mouse zooming via mouse scroll working in Paper.js.
Paper.js doesn't have a wheel
event, so I need to construct a Paper.js Point from the native wheel
event, with correct coordinates, taking into account any View transformations.
For example, this won't work:
const canvas = document.getElementById('canvas')
const tool = new paper.Tool()
paper.setup(canvas)
paper.view.scale(2) // Zoom the view.
// This gives *wrong* coordinates, since we scaled/zoomed the view
// and it's a native event that doesn't take into account PaperJS
// view transformations.
canvas.addEventListener('wheel', e => {
const point = { x: e.offsetX, y: e.offsetY }
console.log(point)
})
// This gives *correct* coordinates, since it's a PaperJS
// event which takes into account the view transformations.
tool.onMouseUp = e => {
console.log(e.point)
}
canvas[resize] {
width: 100%;
height: 100%;
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.2/paper-core.min.js"></script>
<canvas id="canvas" resize></canvas>
Native events won't have a point
property, so we need to create a point value for it:
let point = paper.DomEvent.getPoint(e)
But since we want the point in relation to the canvas:
let point = paper.DomEvent.getOffset(e, canvas)
With this we can then convert to project space using view.viewToProject()
:
point = paper.view.viewToProject(point)
Here's a working example:
const canvas = document.getElementById('canvas')
const tool = new paper.Tool()
paper.setup(canvas)
paper.view.scale(2) // Zoom the view.
// This now gives *correct* points, taking into account
// the view transformations.
canvas.addEventListener('wheel', e => {
const point = paper.view.viewToProject(paper.DomEvent.getOffset(e, canvas))
console.log(point)
})
tool.onMouseUp = e => {
console.log(e.point)
}
canvas[resize] {
width: 100%;
height: 100%;
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.2/paper-core.min.js"></script>
<canvas id="canvas" resize></canvas>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With