Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

javascript - Resize image and maintain overlay positions

I am resizing an image in Javascript to have the image fill the parent container, with its correct aspect ratio. On top of that image i have items that i need to overlay on the image with specific coordinates.

  • Original image size is: 654px X 418px
  • On top of that image i overlay a few other canvas items at exact coordinates, 56px X 82px
  • I resize the image, keeping correct aspect ratio of 1.56

  • Image container to scale too: 1672px X 829px
  • New image size with correct aspect ratio: 1297px X 829px
  • How do i calculate where the new canvas overlay coordinates are??

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the properties of the image element to determine the scaling factor to apply to the overlay items.

The intrinsic (unscaled) dimensions of an image are:

const unscaledWidth = img.naturalWidth,
  unscaledHeight = img.naturalHeight;

The dimensions of the image as drawn are:

const scaledWidth = img.offsetWidth,
  scaledHeight = img.offsetHeight;

The scaling factors are thus:

const scaleX = scaledWidth / unscaledWidth,
  scaleY = scaledHeight / unscaledHeight;

Ref:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...