Created
March 24, 2021 09:40
-
-
Save AmosAidoo/8c2ff4b75184b4f5aff684af7e612a49 to your computer and use it in GitHub Desktop.
Simple snippet to scale and pan the canvas of a p5.js sketch
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
let x,y,scl,delta,panSpeed | |
let translateX, translateY, prevX, prevY | |
function setup() { | |
createCanvas(400, 400) | |
delta = 1 // Will be -1 or 1 depending on the direction of the pan | |
panSpeed = 6 // How fast does the pan move | |
translateX = width/2 | |
translateY = height/2 | |
scl = 1 // Percentage of scaling | |
} | |
function draw() { | |
background(220) | |
translate(translateX, translateY) | |
scale(scl) | |
rect(0, 0, 50, -50) | |
} | |
function mouseWheel(event) { | |
// Grab the direction of the mouse wheel | |
// Multiply by its inverse to normalize it | |
let dir = Math.abs(event.delta) * (1/event.delta) | |
scl+=-dir*0.1 | |
// Constrain the scaling between 100% and 500% | |
scl = constrain(scl, 1, 5) | |
} | |
function mousePressed() { | |
// Set the previous mouse position once the mouse is pressed | |
prevX = mouseX | |
prevY = mouseY | |
return false | |
} | |
function mouseDragged(event) { | |
// Check if the current mouseX position is on the | |
// left or right side of the previous mouseX position | |
if (mouseX > prevX) { | |
translateX += delta*panSpeed | |
console.log("Dragging to the right") | |
} else if (mouseX < prevX) { | |
translateX -= delta*panSpeed | |
console.log("Dragging to the left") | |
} | |
// Check if the current mouseY position is above | |
// or below the current mouseY position | |
if (mouseY > prevY) { | |
translateY += delta*panSpeed | |
console.log("Dragging to the top") | |
} else if (mouseY < prevY) { | |
translateY -= delta*panSpeed | |
console.log("Dragging to the bottom") | |
} | |
// Update the previous mouse position | |
prevX = mouseX | |
prevY = mouseY | |
// Prevent default browser behaviour | |
return false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment