Canvas Pan & Zoom
by Alice Farmer
HTML
<canvas id="dunGen" width="1000px" height="1000px"></canvas>
CSS
canvas { background-color: black; }
JavaScript
var canvas = document.getElementById('dunGen'),
ctx = canvas.getContext('2d'),
dungeon = $('#dunGen'), //Store the jQuery object to make things easier
scale = 1,
offset = {
x : 0,
y : 0,
lastx : 0,
lasty : 0,
offsetx : 0,
offsety : 0
},
dragging = false,
panning = false;
function render() {
ctx.clearRect(0, 0, 1000, 1000);
ctx.fillStyle = "aliceblue";
ctx.scale(scale, scale);
ctx.translate(offset.offsetx / scale, offset.offsety / scale);
ctx.fillRect(5, 5, 200, 200);
ctx.setTransform(1, 0, 0, 1, 0, 0);
drawStroked(`[${offset.offsetx}, ${offset.offsety}]`, 16.5, 16.5);
}
function drawStroked(text, x, y) {
ctx.font = "16px serif"
ctx.strokeStyle = 'black';
ctx.lineWidth = 3;
ctx.strokeText(text, x, y);
ctx.fillStyle = 'aliceblue';
ctx.fillText(text, x, y);
}
$(document).mousedown(function(e) {
if (e.which === 3) {
panning = true;
} else if (e.which === 1) {
dragging = true;
}
});
$(document).mousemove(function(e) {
offset.lastx = offset.x;
offset.lasty = offset.y;
offset.x = e.pageX;
offset.y = e.pageY;
if (panning) {
if (offset.lastx > offset.x) {
for (var i = offset.x; i < offset.lastx; i++) {
offset.offsetx--;
}
} else if (offset.lastx < offset.x) {
for (var i = offset.lastx; i < offset.x; i++) {
offset.offsetx++;
}
}
if (offset.lasty > offset.y) {
for (var i = offset.y; i < offset.lasty; i++) {
offset.offsety--;
}
} else if (offset.lasty < offset.y) {
for (var i = offset.lasty; i < offset.y; i++) {
offset.offsety++;
}
}
render();
}
if (dragging) {
//Dragging code goes here
}
});
$(document).mouseup(function(e) {
panning = false;
dragging = false;
});
dungeon.contextmenu( function() {
return false;
});
dungeon.bind("DOMMouseScroll", function(e) {
var axis = e.originalEvent.axis; //1 is side scroll, 2 is normal scroll
var delta =...