PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 30, 2022

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

 July 30, 2022     image, javascript, konva, konvajs     No comments   

Issue

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

enter image description here

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

enter image description here

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

Solution

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


Answered By - chonglawr
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing