Изменение размера изображения на холсте HTML5 с помощью JavaScript: методы и примеры

Чтобы изменить размер изображения на холсте HTML5 с помощью JavaScript, можно использовать несколько методов. Вот несколько часто используемых подходов:

Метод 1: использование метода drawImage()

// Get the canvas element and its 2D context
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// Create an image object
var img = new Image();
// Set the source of the image
img.src = 'path/to/image.jpg';
// Once the image loads, resize and draw it on the canvas
img.onload = function() {
  // Set the new desired width and height
  var newWidth = 200;
  var newHeight = 200;
  // Draw the resized image on the canvas
  ctx.drawImage(img, 0, 0, newWidth, newHeight);
};

Метод 2: использование метода Scale()

// Get the canvas element and its 2D context
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// Create an image object
var img = new Image();
// Set the source of the image
img.src = 'path/to/image.jpg';
// Once the image loads, resize and draw it on the canvas
img.onload = function() {
  // Set the scaling factors
  var scaleX = 0.5;
  var scaleY = 0.5;
  // Scale the canvas context
  ctx.scale(scaleX, scaleY);
  // Draw the image on the canvas (scaled)
  ctx.drawImage(img, 0, 0);
};

Метод 3: использование метода createImageBitmap()

// Get the canvas element and its 2D context
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// Create an image object
var img = new Image();
// Set the source of the image
img.src = 'path/to/image.jpg';
// Once the image loads, resize and draw it on the canvas
img.onload = function() {
  // Set the new desired width and height
  var newWidth = 200;
  var newHeight = 200;
  // Create an image bitmap from the original image
  createImageBitmap(img)
    .then(function(imageBitmap) {
      // Draw the resized image on the canvas
      ctx.drawImage(imageBitmap, 0, 0, newWidth, newHeight);
    });
};