乐闻世界logo
搜索文章和话题

Scaling an image to fit on canvas

1个答案

1

In HTML5, the Canvas API provides powerful drawing capabilities, including scaling images to fit the canvas dimensions. Below, I will provide a detailed explanation of how to achieve this functionality, along with a specific code example.

First, we need to create an HTML page and define the canvas element within it:

html
<!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="500" height="400" style="border:1px solid #000000;"> Your browser does not support Canvas. </canvas> <script src="script.js"></script> </body> </html>

Next, we write JavaScript code in the script.js file to handle image loading and scaling:

javascript
window.onload = function() { var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); // Create a new Image object var img = new Image(); // Set the image source URL img.src = 'path/to/your/image.jpg'; // Wait for the image to load before drawing img.onload = function() { // Get the canvas dimensions var canvasWidth = canvas.width; var canvasHeight = canvas.height; // Calculate the scaling ratio var scaleWidth = canvasWidth / img.width; var scaleHeight = canvasHeight / img.height; var scale = Math.min(scaleWidth, scaleHeight); // Calculate the starting coordinates to center the image var x = (canvasWidth - img.width * scale) / 2; var y = (canvasHeight - img.height * scale) / 2; // Draw the image ctx.drawImage(img, x, y, img.width * scale, img.height * scale); }; };

In this code, we first create an Image object and set its source to the URL of the desired image. By listening to the onload event, we ensure that drawing occurs only after the image has loaded. Within the callback function for image load completion, we calculate the scaling ratio by comparing the canvas dimensions to the image dimensions and taking the smaller value to ensure the image is fully visible and fits the canvas. Next, we compute the starting coordinates for drawing to center the image on the canvas. Finally, we use the drawImage method to render the image onto the canvas.

This approach guarantees that regardless of the original image's dimensions, it adapts to the given canvas size while preserving the aspect ratio, thereby avoiding distortion.

2024年6月29日 12:07 回复

你的答案