In the following p5.js code I'm trying to create 2 separate methods.
centerInWindow() is meant to keep the image centered in the canvas while it's being scaled down after the user clicks on the canvas.
centerToClick() is meant to keep the image centered on the point the user clicked on, while it's being scaled up.
None of them work and I'm having trouble getting the logic right.
function centerInWindow(img) {
let currentSize = img.width * currentScale
imgX = (windowWidth / 2) - (currentSize / 2)
imgY = (windowHeight / 2) - (currentSize / 2)
}
function centerToClick() {
imgX = clickX * currentScale
imgY = clickY * currentScale
}
let minScale = 1
let maxScale = 5
let targetScale = minScale
let currentScale = targetScale
let clickX, clickY, imgX, imgY
let idx = 0
function setup() {
pixelDensity(1)
createCanvas(windowWidth, windowHeight)
preload(IMG_PATHS, IMGS)
frameRate(12)
}
function draw() {
clear()
if (currentScale < targetScale) {
currentScale += 0.05
if (currentScale > targetScale) {
currentScale = targetScale
}
centerToClick()
} else if (currentScale > targetScale) {
currentScale -= 0.05
if (currentScale < targetScale) {
currentScale = targetScale
}
centerInWindow(IMGS[idx])
} else {
centerInWindow(IMGS[idx])
}
scale(currentScale)
image(IMGS[idx], imgX, imgY)
idx++
if (idx === IMGS.length) {
idx = 0
}
}
window.addEventListener('click', function({ clientX, clientY }) {
targetScale = targetScale === maxScale ? minScale : maxScale
clickX = clientX
clickY = clientY
})
See it in action here.
Any help would be appreciated.

