How to reduce canvas stroke with animation?

by arnoldo.moen , in category: HTML & CSS , a year ago

How to reduce canvas stroke with animation?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , a year ago

@arnoldo.moen 

To reduce canvas stroke with animation, you can use JavaScript and CSS to create the desired effect. Here's an example of how you can achieve this:

  1. HTML:
1
 <canvas id="myCanvas" width="500" height="500"></canvas>


  1. CSS: #myCanvas { border: 1px solid black; background-color: white; }
  2. JavaScript: // Get the canvas element and its context const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); // Initialize the stroke width and animation effect let strokeWidth = 10; let animationId = null; // Function to reduce the stroke width with animation function reduceStrokeWidth() { if (strokeWidth > 0) { // Clear the canvas ctx.clearRect(0, 0, canvas.width, canvas.height); // Reduce the stroke width strokeWidth -= 1; // Set the new stroke width ctx.lineWidth = strokeWidth; // Draw a rectangle with the reduced stroke width ctx.strokeRect(50, 50, 400, 400); // Request the next frame of the animation animationId = window.requestAnimationFrame(reduceStrokeWidth); } else { // Animation completed, cancel the animation frame window.cancelAnimationFrame(animationId); } } // Start the animation reduceStrokeWidth();


In this example, we start with a canvas element with id "myCanvas". The CSS ensures that the canvas has a border and a white background.


The JavaScript code gets the canvas element and its 2D context. We initialize the stroke width to a value (e.g., 10) and create a variable to store the animation frame ID.


The "reduceStrokeWidth" function is defined to handle the animation effect. It checks if the stroke width is greater than 0. If it is, it clears the canvas, reduces the stroke width by 1, sets the new stroke width in the context, and draws a rectangle using the strokeRect() method. Then, it requests the next frame of the animation by calling requestAnimationFrame() and assigns the returned ID to the animationId variable. If the stroke width reaches 0, the animation is completed, and the cancelAnimationFrame() method is called to stop the animation loop.


Finally, we call the reduceStrokeWidth() function to start the animation.


This code will continuously reduce the stroke width of the rectangle using animation until it reaches 0.