Background size and background position of img tag

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

The logic was originally just a few uploaded images (in <img>

) sitting side-by-side with little edit buttons above them that open a popup with cropping logic. However, the BOM should now have a preview of what has been clipped.

The question is - is there a way to do this without switching everything <img>

in <div>

, which will have all the images as a background and can be moved and scaled to show the cropped part? Is there an analogue of this style or other possible solution where I can store tags <img>

?

+3


source to share


2 answers


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

It doesn't matter which element you use, it can be anything (see w3.org/TR/CSS2/colors.html ), including the 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;" />

      



Please note, if you are using an image tag, you must remove the attribute src

(like JavaScript). Otherwise, the background image will not be visible.

However, I would recommend that you use the JavaScript / Plugin library instead of writing something on your own. There are many solutions:

+1


source


There is no easy way. If included a link to one answer below that agree. You can use javscript to render a portion of the image to the canvas, and then use the answer I posted in the (Canvas Approach) section below to set the resulting image to the src attribute of the image tag.

Consistent answer: Offset visible image in <img> tags similar to background image



Canvas approach: Is it possible to get an image from the canvas element and use it in the img src tag?

0


source







All Articles