我想以網格模式將影像添加到 HTML5 畫布。畫布是方形的,但影像具有各種尺寸和縱橫比。我想將所有影像裁剪成正方形。
我有演算法將影像作為正方形放置在畫布上,但影像被拉伸/擠壓。

如何將橫向和/或縱向影像裁剪成正方形。
這是演算法:
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';
}
}
如何裁剪影像:

uj5u.com熱心網友回復:
您的嵌套 for 回圈執行img.onload25img.src = 'https://source.unsplash.com/random';次。
let ii = 0;
for (let xCell = 0; xCell < 5; xCell ) {
for (let yCell = 0; yCell < 5; yCell ) {
console.log( ii ": ", xCell, yCell);
}
}
這是使用四個預定 x,y 坐標組的一種方法:
[[0,0],[200,0],[0,200],[200,200]].forEach(function ([x,y]) {
console.log(x,y);
});
要在HTML Canvas 元素中裁剪和放置影像,您需要使用所有可用drawImage()引數。首先裁剪(并在必要時調整大小)您正在加載的影像,然后將其放在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
)
例如:
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>
uj5u.com熱心網友回復:
看看這個檔案
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492030.html
標籤:javascript 算法 html5-画布
