Canvas zoom in and zoom out

On mouse wheel zoom in and out

by Suryar Praveen

HTML

<canvas id="canvas" height='500' width='900'></canvas>

CSS

canvas {
  border: 2px solid black;
}

JavaScript

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var scale = 1;
var currentzoom = 1;
var originx = 0;
var originy = 0;

function draw() {
  context.fillStyle = "white";
  context.fillRect(originx, originy, canvas.width / scale, canvas.height / scale);
  context.fillStyle = "black";
  context.fillRect(50, 50, canvas.width / 2, canvas.height / 2);
}
setInterval(draw, 100);

var mousex = 0,
  mousey = 0;

canvas.onmousewheel = function(event) {
  var wheel = event.wheelDelta / 120; //n or -n

  var zoom = 0;
  if (wheel < 0) {
    zoom = 1 / 2;
    if (currentzoom == 1)
      return;
  } else {
    mousex = event.clientX - canvas.offsetLeft;
    mousey = event.clientY - canvas.offsetTop;
    zoom = 2;
    if (currentzoom == 32)
      return;
  }
  currentzoom *= zoom;

  context.translate(
    originx,
    originy
  );
  context.scale(zoom, zoom);
  context.translate(
    -(mousex / scale + originx - mousex / (scale * zoom)),
    -(mousey / scale + originy - mousey / (scale * zoom))
  );

  originx = (mousex / scale + originx - mousex / (scale * zoom));
  originy = (mousey / scale + originy - mousey / (scale * zoom));
  scale *= zoom;
}