Reputation: 211
In my project, I have a konva canvas where I can add items. I default these item images to a height and width of 200. When trying to apply a crop to the item, the crop ignores the resized image dimensions. It crops the image size to the correct height and width but the image itself returns back to its original dimensions. Is there an easy way to fix this? I saw this being asked KonvaJS crop and resize but that deals with a manual resizing of images.
image when loaded with original dimensions 394 x 387 that is resized to 200 x 200 image in a 200 x 200 area
when trying to crop the image of 8 pixels, the image reverts back to 394 x 387 and crops to 386 x 387 in an image area of 192 x 200
addItem = (imgUrl) => {
const img = new (window as any).Image();
img.onload = () => {
const width, height = 200;
img.width = 200;
img.height = 200;
const newImg = new Konva.Image({ width, height, image: img, draggable: true });
this.layer.add(newImg);
this.layer.draw();
};
img.src = imageUrl;
}
cropItem = (item) => {
item.crop({
x: item.cropX() + 8,
y: item.cropY() + 0,
width: item.width() - 8,
height: item.height() - 0
});
item.width(item.width() - 8);
this.layer.draw();
}
Upvotes: 2
Views: 828
Reputation: 211
You will need to use scaleX and scaleY
addItem = (imgUrl) => {
const img = new (window as any).Image();
img.onload = () => {
const { width, height } = image;
const desiredWidth = 200;
const desiredHeight = 200;
const scaleX = desiredWidth / width;
const scaleY = desiredHeight / height;
const newImg = new Konva.Image({ width, height, image: img, scaleX, scaleY, draggable: true });
this.layer.add(newImg);
this.layer.draw();
};
img.src = imageUrl;
}
Upvotes: 1