puzzle/game/Camera.js

73 lines
1.8 KiB
JavaScript
Raw Normal View History

2020-11-07 11:35:29 +01:00
import BoundingRectangle from "./BoundingRectangle.js"
export default class Camera {
constructor(canvas) {
this.x = 0
this.y = 0
2020-11-07 17:49:42 +01:00
// TODO: when canvas resizes, this should
2020-11-07 11:35:29 +01:00
// syncronize with the cam
this.width = canvas.width
this.height = canvas.height
this.zoom = 1
this.minZoom = .2
this.maxZoom = 6
this.zoomStep = .05
}
rect() {
2020-11-08 14:13:43 +01:00
return new BoundingRectangle(
- this.x,
- this.x + (this.width / this.zoom),
- this.y,
- this.y + (this.height / this.zoom),
)
2020-11-07 11:35:29 +01:00
}
2020-11-07 17:49:42 +01:00
2020-11-07 11:35:29 +01:00
move(x, y) {
this.x += x / this.zoom
this.y += y / this.zoom
}
zoomOut() {
const newzoom = Math.max(this.zoom - this.zoomStep, this.minZoom)
if (newzoom !== this.zoom) {
// centered zoom
this.x -= ((this.width / this.zoom) - (this.width / newzoom)) / 2
this.y -= ((this.height / this.zoom) - (this.height / newzoom)) / 2
this.zoom = newzoom
return true
}
return false
}
zoomIn() {
const newzoom = Math.min(this.zoom + this.zoomStep, this.maxZoom)
if (newzoom !== this.zoom) {
// centered zoom
this.x -= ((this.width / this.zoom) - (this.width / newzoom)) / 2
this.y -= ((this.height / this.zoom) - (this.height / newzoom)) / 2
this.zoom = newzoom
return true
}
return false
}
translateMouse(mouse) {
return {
x: (mouse.x / this.zoom) - this.x,
y: (mouse.y / this.zoom) - this.y,
}
}
2020-11-07 17:49:42 +01:00
translateMouseBack(mouse) {
return {
x: (mouse.x + this.x) * this.zoom,
y: (mouse.y + this.y) * this.zoom,
}
}
}