user1361529
user1361529

Reputation: 2697

scaling an SVG over an image that resizes without jquery

lets suppose I have an image of dimensions 1280x720

I have some polygons that are computed by a server on top of the original sized images that need to be drawn on top of this image. They are

<polygon points="531,243,687,316,663,593,360,717,191,520" />                                    
<polygon points="275,17,422,45,412,312,271,235" />
<polygon points="929,180,1108,248,985,707,847,676" />
<polygon points="598,70,700,101,658,531,516,436" />

Now I need to display the image and overlay these polygons on top of it. The problem however is that the image is scaled by the browser depending on the window size, which is dynamic. The image is displayed using object-fit-contain CSS so the size changes as I resize.

How do I ensure the SVG co-ordinates above auto scale?

I've read about viewBox but I'm not really looking to specify my own co-ordinates here. The issue is I don't really know how the image will be displayed/sized by the browser as it will depend on the window.

thanks

Upvotes: 2

Views: 524

Answers (3)

Dawnb
Dawnb

Reputation: 116

You can use <image> element inside the <svg> tag, then they will become one, you can do any scale with it.

Here is an SVG image example:

<svg xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink">

  <rect x="10" y="10" height="130" width="500" style="fill: #000000"/>

  <image x="20" y="20" width="300" height="80"
     xlink:href="http://jenkov.com/images/layout/top-bar-logo.png" />

  <line x1="25" y1="80" x2="350" y2="80"
            style="stroke: #ffffff; stroke-width: 3;"/>
</svg>

Reference: SVG image element

Upvotes: 0

Paul LeBeau
Paul LeBeau

Reputation: 101800

The default scaling behaviour of SVGs is the same as object-fit: contain. So all you should need to do is set the SVG's viewBox width and height to the same dimensions as the image.

So, for instance, if your image is 640x480, set your viewBox to "0 0 640 480".

div {
  position: relative;
}

div > img,
div > svg {
  width: 100%;
  height: 200px;
}

img {
  object-fit: contain;
}

svg {
  position: absolute;
  top: 0;
}
<div>
  <img src="http://lorempixel.com/output/people-q-c-640-480-1.jpg"/>
  
  <svg viewBox="0 0 640 480">
    <circle cx="450" cy="215" r="40" fill="none" stroke="red" stroke-width="10"/>
  </svg>
</div>

Upvotes: 1

Chilled_
Chilled_

Reputation: 13

Could you avoid doing this with html in any way? A simple image editor seems like a better way of doing this, but I can't say because I don't know your circumstances. Otherwise you could probably use margin for the placement.

Upvotes: 0

Related Questions