简体   繁体   中英

Background-size and background-position on an img tag

I have an image that can be cropped used a JS lib. The lib returns x,y, width and height of the selection.

Initially, the logic was just several uploaded image (in <img> ) sit side by side with little edit buttons over them that open a pop-up with the cropping logic. However, now the specification is to have the preview of what was cropped.

The question - is there a way to do it without switching all <img> to <div> s that will have all images as background and can be moved and scaled to show the cropped part? Is there a counterpart to such styling or another possible workaround in which I can keep the <img> tags?

If you don't care about IE you can use object-fit and object-position :

img {
   object-fit: cover;
   object-position: center top;
}

The best way to achieve this is by using any html element in combination with the css background attribute. Within that attribute you can define margins as sizes to position and resize the background image. In your case that element would have the width and the height given by your crop library. The position of the background image would be x and y (also from the library), but inverted.

It does not matter which element you use, it can be any (See w3.org/TR/CSS2/colors.html ), included an img tag as shown in the following example :

<img border="0" style="display:block; width:120px; height:120px; background-color:red; padding:9px; background:url(http://www2.cnrs.fr/sites/communique/image/mona_unvarnish_web_image.jpg) no-repeat; background-position:-100px -40px;" />

Note that if you use the image tag you have to remove the src attribute (eg by JavaScript). Otherwise the background image will not be visible.

Nevertheless I would recommend you to use a JavaScript Library / Plugin instead of writing it something by your own. There are a bunch of solutions:

There is not a simple way. If included a link to one answer below that agrees. You could use javscript to render part of the image to a canvas then use the answer I've posted under (Canvas Approach) below to set the resulting image into the image tag src attribute.

Concurring Answer: Offset viewable image in <img> tags the same way as for background-image

Canvas Approach: Can I get image from canvas element and use it in img src tag?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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