72 lines
2.4 KiB
JavaScript
72 lines
2.4 KiB
JavaScript
import { Tool } from '../tool.js';
|
|
import {
|
|
ZOOM_IN_FACTOR,
|
|
ZOOM_OUT_FACTOR,
|
|
} from '../config.js';
|
|
|
|
export class Zoom extends Tool {
|
|
constructor(toolbar) {
|
|
super(toolbar);
|
|
|
|
const zoomOut = document.createElement('button');
|
|
const zoomIn = document.createElement('button');
|
|
const zoomAll = document.createElement('button');
|
|
|
|
this.div.appendChild(zoomOut);
|
|
this.div.appendChild(zoomIn);
|
|
this.div.appendChild(document.createElement('br'));
|
|
this.div.appendChild(zoomAll);
|
|
this.div.appendChild(document.createElement('br'));
|
|
|
|
zoomAll.classList.add('wide');
|
|
|
|
zoomOut.innerHTML = '<h2>Zoom<br>Out</h2>';
|
|
zoomIn.innerHTML = '<h2>Zoom<br>In</h2>';
|
|
zoomAll.innerHTML = '<h2>Zoom to Fit</h2>';
|
|
|
|
zoomOut.addEventListener('click', () => {
|
|
// Aim at center of view
|
|
const x = this.sim.display.width * this.sim.display.scale / 2;
|
|
const y = this.sim.display.height * this.sim.display.scale / 2;
|
|
this.sim.scheduleZoom(this.sim.screenToSim(x, y), ZOOM_OUT_FACTOR);
|
|
});
|
|
|
|
zoomIn.addEventListener('click', () => {
|
|
// Aim at center of view
|
|
const x = this.sim.display.width * this.sim.display.scale / 2;
|
|
const y = this.sim.display.height * this.sim.display.scale / 2;
|
|
this.sim.scheduleZoom(this.sim.screenToSim(x, y), ZOOM_IN_FACTOR);
|
|
});
|
|
|
|
zoomAll.addEventListener('click', () => {
|
|
// Determine bounding box
|
|
const box = this.sim.objects.boundingBox;
|
|
const x = (box.start.x + box.end.x) / 2;
|
|
const y = (box.start.y + box.end.y) / 2;
|
|
const widthRatio = Math.abs(box.start.x - box.end.x) / this.sim.display.width;
|
|
const heightRatio = Math.abs(box.start.y - box.end.y) / this.sim.display.height;
|
|
const biggerRatio = Math.max(widthRatio, heightRatio);
|
|
const base2factor = Math.log(1/biggerRatio) / Math.log(2) - 1;
|
|
const factor = Math.floor(base2factor);
|
|
// Determine average momentum and set panning velocity to match
|
|
const netMomentum = {x: 0, y: 0};
|
|
let totalMass = 0;
|
|
let count = 0;
|
|
this.sim.objects.forEachObject(obj => {
|
|
count++;
|
|
netMomentum.x += obj.mass * obj.velocity.x;
|
|
netMomentum.y += obj.mass * obj.velocity.y;
|
|
totalMass += obj.mass;
|
|
});
|
|
if (!count) {
|
|
return;
|
|
}
|
|
const netVelocity = {
|
|
x: netMomentum.x / totalMass,
|
|
y: netMomentum.y / totalMass,
|
|
};
|
|
this.sim.scheduleZoom({x, y}, factor, netVelocity)
|
|
});
|
|
}
|
|
}
|