How to implement zoom animation in canvas?

by dalton_moen , in category: Javascript , 3 months ago

How to implement zoom animation in canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 3 months ago

@dalton_moen 

You can implement a zoom animation in canvas using JavaScript. Here is a simple example to show you how it can be done:

  1. Create a canvas element in your HTML file:
1
<canvas id="canvas" width="400" height="400"></canvas>


  1. Create a JavaScript file and write the following code to implement the zoom animation:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

let scale = 1.0;
let targetScale = 1.0;
const scaleSpeed = 0.05;

function update() {
  const dx = targetScale - scale;
  scale += dx * scaleSpeed;

  // Clear the canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Save the current transformation matrix
  ctx.save();

  // Translate to the center of the canvas
  ctx.translate(canvas.width / 2, canvas.height / 2);
  
  // Scale the canvas
  ctx.scale(scale, scale);

  // Draw something (e.g. a square)
  ctx.fillStyle = 'red';
  ctx.fillRect(-50, -50, 100, 100);

  // Restore the transformation matrix
  ctx.restore();

  requestAnimationFrame(update);
}

// Update the target scale when the mouse wheel event is fired
canvas.addEventListener('wheel', function(event) {
  targetScale -= event.deltaY * 0.001;
});

update();


This code sets up a canvas element, creates a function to update the canvas with the zoom animation, and listens for mouse wheel events to update the target scale of the canvas. As the user scrolls, the canvas will zoom in and out accordingly. You can customize this code to create different zoom animations or effects in your canvas.