minezo-www/static/map.js
2024-10-17 16:07:30 -04:00

140 lines
No EOL
2.9 KiB
JavaScript

const mapWidth = 10000;
const mapHeight = 10000;
let assets = [
'base.png',
'pol.svg'
]
let imgA = [];
let map = document.querySelector('.map');
let ctx = map.getContext('2d');
let coords = document.querySelector('.coords');
let pos = [];
let mpos = [0, 0];
let keys = [];
let vel = [0, 0];
let center = [0, 0];
let lastPos = [0, 0];
let isMouse = false;
let zoom = 1;
let timer = 0;
let id = '';
ctx.imageSmoothingEnabled = false;
function fixEvent(e) {
let r = map.getBoundingClientRect();
e = { clientX: e.clientX, clientY: e.clientY };
e.clientX -= r.x;
e.clientY -= r.y;
e.clientX /= r.width / map.width;
e.clientY /= r.height / map.height;
return e;
}
function down(e) {
keys[e.key.toLowerCase()] = true;
};
function up(e) {
keys[e.key.toLowerCase()] = false;
};
function mouseMove(e) {
e = fixEvent(e);
lastPos = [e.clientX, e.clientY];
if (!isMouse) return;
mpos[0] += e.clientX - center[0];
mpos[1] += e.clientY - center[1];
center = lastPos;
}
function mouseUp(e) {
isMouse = false;
}
function mouseDown(e) {
e = fixEvent(e);
if (e.button == '2') return;
isMouse = true;
center = [e.clientX, e.clientY];
}
function wheel(e) {
document.body.style.overflow = 'hidden';
if (timer != 0) clearTimeout(timer);
timer = setTimeout(function() {
document.body.style.overflow = '';
},400)
mpos[0] -= lastPos[0];
mpos[1] -= lastPos[1];
let f = (2 ** -(e.deltaY/256));
mpos[0] *= f;
mpos[1] *= f;
mpos[0] += lastPos[0];
mpos[1] += lastPos[1];
zoom *= f;
}
function move() {
var isShift = keys['q'];
vel[0] += ((keys['a'] ? 1 : 0) - (keys['d'] ? 1 : 0)) * (isShift ? 5 : 1);
vel[1] += ((keys['w'] ? 1 : 0) - (keys['s'] ? 1 : 0)) * (isShift ? 5 : 1);
vel[0] *= 0.9;
vel[1] *= 0.9;
mpos[0] += vel[0];
mpos[1] += vel[1];
ctx.clearRect(0, 0, map.width, map.height);
for (let img of imgA) {
let w = img.width * zoom;
let h = img.height * zoom;
ctx.drawImage(img, mpos[0], mpos[1], w, h)
}
off = [-(imgA[0].width * zoom - map.width) / 2, -(imgA[0].height * zoom - map.height) / 2];
coords.textContent = `X: ${(mpos[0] - off[0]) * mapWidth / imgA[0].width / -zoom}\nZ: ${(mpos[1] - off[1]) * mapHeight / imgA[0].height / -zoom}`;
}
for (let asset of assets) {
let img = new Image();
img.src = `/static/${asset}`;
imgA.push(img);
}
let off = [-(imgA[0].width * zoom - map.width) / 2, -(imgA[0].height * zoom - map.height) / 2];
mpos = [off[0], off[1]];
setInterval(move, 10);
window.addEventListener('keydown', down);
window.addEventListener('keyup', up);
map.addEventListener('wheel', wheel);
window.addEventListener('mousemove', mouseMove);
window.addEventListener('mousedown', mouseDown);
window.addEventListener('mouseup', mouseUp);
function copy() {
let addr = 'play.xuyezo.net';
navigator.clipboard.writeText(addr);
alert(addr);
}