Quiero agregar imágenes a un lienzo HTML5 en un patrón de cuadrícula. El lienzo es cuadrado pero las imágenes son de varios tamaños y proporciones. Quiero recortar todas las imágenes en cuadrados.
Tengo el algoritmo para colocar las imágenes en el lienzo como cuadrados, pero las imágenes se estiran/aprietan.
Cómo recortar las imágenes de paisajes o retratos en cuadrados.
Aquí está el algoritmo:
const ctx = canvas.getContext("2d"); for (let xCell = 0; xCell < 5; xCell++) { for (let yCell = 0; yCell < 5; yCell++) { const x = xCell * 200; const y = yCell * 200; const img = new Image(); img.onload = function() { // how to crop into squares? ctx.drawImage(img, x, y, 200, 200); }; img.src = 'https://source.unsplash.com/random'; } }Sus bucles for anidados ejecutan img.onload e img.src = 'https://source.unsplash.com/random'; 25 veces
let ii = 0; for (let xCell = 0; xCell < 5; xCell++) { for (let yCell = 0; yCell < 5; yCell++) { console.log(++ii + ": ", xCell, yCell); } }Aquí hay una forma de usar cuatro grupos de coordenadas x, y predeterminados:
[[0,0],[200,0],[0,200],[200,200]].forEach(function ([x,y]) { console.log(x,y); }); Para recortar y colocar una imagen en un elemento HTML Canvas , debe usar todos los parámetros drawImage() disponibles. Primero recorte (y cambie el tamaño si es necesario) la imagen que está cargando, luego colóquela en el canvas .
drawImage(image, // source image crop and resize // sx, sy = upper left coordinates of crop location // sWidth, sHeight = dimensions of crop sx, sy, sWidth, sHeight, // placement of image on canvas // dx, dy = upper left coordinates of placement // dWidth, dHeight = dimensions of placement on canvas dx, dy, dWidth, dHeight )Por ejemplo:
const ctx = document.querySelector("canvas").getContext("2d"); // loop array of 4 [x,y] desired coordinates [[0,0],[200,0],[0,200],[200,200]].forEach(function ([x,y]) { const img = new Image(); img.src = 'https://images.unsplash.com/photo-1652957251843-dcc1a7cfc4be?w=1080'; img.onload = function() { const [imgw, imgh] = [this.width, this.height]; ctx.drawImage(img, // crop (250, 350) and resize ((imgw / 2.5), (imgh / 2.5)) source image 250, 350, (imgw / 2.5), (imgh / 2.5), // place image on canvas x, y, 200, 200 ); }; }); <canvas width="400" height="400"></canvas>Echa un vistazo a esta documentación.
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) 