Я хочу знать, как мы можем масштабировать и обрезать изображение в Javascript. Я хочу уменьшить его до 300x300px и немного обрезать. Есть ли у вас какие-либо предложения ? У меня есть следующий код:
function cropImage(imagePath, newX, newY, newWidth, newHeight) {
//create an image object from the path
var img = document.createElement('img');
img.src = "data:image/png;base64,"+imagePath;
//alert(img.width);
//alert(img.height);
//initialize the canvas object
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
//set the canvas size to the new width and height
canvas.width = 300;
canvas.height = 300;
//draw the image
ctx.drawImage(img, newX, 75, 300, 300, 0, 0, 300, 300);
variables.imageCrop = canvas.toDataURL();}
Спасибо !



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Попробуй это:
И узнайте больше о .drawImage()
function cropImage(imagePath, leftRight, topBottom, newWidth, newHeight) {
const img = document.createElement('img');
img.src = imagePath;
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
img.addEventListener('load', function() {
//Set your canvas size as your choice
//here i just scaled by 10 with original dimension
canvas.width = img.naturalWidth*10;
canvas.height = img.naturalHeight*10;
const cropLeft = leftRight[0];
const cropRight = img.naturalWidth - leftRight[0] - leftRight[1];
const cropTop = topBottom[0];
const cropBottom = img.naturalHeight - topBottom[0] - topBottom[1];
ctx.drawImage(
img,
cropLeft,cropTop,
cropRight, cropBottom,
0,0, //here you can control placement of cropped image from left and top, by default it stays in 0,0 meaning the top left corner of the canvas
newWidth,newHeight //new width and height of cropped image
);
});
}
//Size of this image is 100x100 px
const img = "https://dummyimage.com/100.png/09f/fff";
//here [10,10] meaning crop 10px from left and 10px from right
//here [20,20] meaning crop 20px from top and 20px from bottom
cropImage(img,[10,10],[20,20], 100, 100);URL-адрес на 100% правильный, не беспокойтесь об этом, изображение отображается хорошо. Моя проблема в том, что я хочу обрезать изображение, например, я хочу удалить 50 пикселей слева и справа, я не могу этого сделать, могу ли я добавить еще один drawImage?
@AdamHarmand Теперь я понимаю, чего вы хотите достичь, я реорганизовал коды в соответствии с вашими требованиями, а также добавил некоторые комментарии.
imagePathэто URL?