JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="myCanvas" width="400" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
JavaScript
var transform = {x: 0, y: 0, scale: 1},
ctx = document.getElementById('myCanvas').getContext("2d");
function scaleCanvas(scale, point) {
var oldScale = transform.scale;
transform.scale = scale / transform.scale;
// Re-centre the canvas around the zoom point
transform.x += point.x / transform.scale - point.x / oldScale;
transform.y += point.y / transform.scale - point.y / oldScale;
setTransform();
}
function dragCanvas(x,y) {
transform.x += x / transform.scale;
transform.y += y / transform.scale;
setTransform();
}
function setTransform() {
ctx.setTransform(transform.scale, 0, 0, transform.scale, transform.x, transform.y);
}
ctx.fillRect(10, 10, 100, 50);
dragCanvas(10, 10);
ctx.fillStyle = "blue";
ctx.fillRect(10, 10, 100, 50);
scaleCanvas(2, {x: 100, y: 50});
ctx.fillStyle = "red";
ctx.fillRect(5, 5, 100, 50);