Created
November 1, 2018 23:11
-
-
Save companje/5478fff07a18a1f4806df4cf77ae1048 to your computer and use it in GitHub Desktop.
Pan / Zoom P5.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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
Got this working on repl.it:
https://repl.it/@JohnGlazebrook/p5-js-pan-zoom
https://p5-js-pan-zoom.johnglazebrook.repl.co/