Skip to content

Instantly share code, notes, and snippets.

@benfavre
Forked from companje/PanZoom.js
Created March 9, 2020 00:31
Show Gist options
  • Save benfavre/89d6288f70d9550145a47465f137caee to your computer and use it in GitHub Desktop.
Save benfavre/89d6288f70d9550145a47465f137caee to your computer and use it in GitHub Desktop.
Pan / Zoom P5.js
<html>
<head>
<meta charset="UTF-8">
<script language="javascript" type="text/javascript" src="libraries/p5.js"></script>
<script language="javascript" type="text/javascript" src="PanZoomP5js.js"></script>
<!-- This line removes any default padding and style.
You might only need one of these values set. -->
<style> body {padding: 0; margin: 0;} </style>
</head>
<body>
</body>
</html>
//Zoom/Pan Component
//by Rick Companje, Nov 1, 2018.
//Enjoy!
var img;
var w, h, tow, toh;
var x, y, tox, toy;
var zoom = .01; //zoom step per mouse tick
function preload() {
img = loadImage("https://i.imgur.com/9dbblSn.jpg");
}
function setup() {
createCanvas(windowWidth, windowHeight);
w = tow = img.width;
h = toh = img.height;
x = tox = w / 2;
y = toy = h / 2;
}
function draw() {
background(0);
//tween/smooth motion
x = lerp(x, tox, .1);
y = lerp(y, toy, .1);
w = lerp(w, tow, .1);
h = lerp(h, toh, .1);
image(img, x-w/2, y-h/2, w, h);
}
function mouseDragged() {
tox += mouseX-pmouseX;
toy += mouseY-pmouseY;
}
function mouseWheel(event) {
var e = -event.delta;
if (e>0) { //zoom in
for (var i=0; i<e; i++) {
if (tow>30*width) return; //max zoom
tox -= zoom * (mouseX - tox);
toy -= zoom * (mouseY - toy);
tow *= zoom+1;
toh *= zoom+1;
}
}
if (e<0) { //zoom out
for (var i=0; i<-e; i++) {
if (tow<width) return; //min zoom
tox += zoom/(zoom+1) * (mouseX - tox);
toy += zoom/(zoom+1) * (mouseY - toy);
toh /= zoom+1;
tow /= zoom+1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment