简体   繁体   English

调整大小后如何裁剪 konva 图像?

[英]How do I crop a konva image when it has been resized?

In my project, I have a konva canvas where I can add items.在我的项目中,我有一个 konva 画布,可以在其中添加项目。 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.我默认这些项目图像的高度和宽度为 200。当尝试对项目应用裁剪时,裁剪会忽略调整大小的图像尺寸。 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.我看到有人问KonvaJS 裁剪和调整大小,但这涉及手动调整图像大小。

image when loaded with original dimensions 394 x 387 that is resized to 200 x 200 image in a 200 x 200 area加载原始尺寸为 394 x 387 的图像,在 200 x 200 区域中调整为 200 x 200 图像

在此处输入图像描述

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尝试裁剪 8 像素的图像时,图像恢复为 394 x 387 并在 192 x 200 的图像区域中裁剪为 386 x 387

在此处输入图像描述

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();
}

You will need to use scaleX and scaleY您将需要使用 scaleX 和 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;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM