Select image with image element in chrome

I need to reuse the displayed image of an image element. Is there a direct way to use javascript to access the image file path displayed by chrome / opera without having to replicate the logic that completes the image creation.

<picture>
  <source media="(min-width: 800px)" srcset="head.jpg, head-2x.jpg 2x">
  <source media="(min-width: 450px)" srcset="head-small.jpg, head-small-2x.jpg 2x">
  <img src="head-fb.jpg" srcset="head-fb-2x.jpg 2x" >
</picture>

Using the example above, in the browser window for the retina with a width of 1200 pixels, an image-enabled browser will display head-2x.jpg. Or, if I use a Chrome browser on a smartphone with a width of less than 450 pixels with a retina display, it will use head-fb-2x.jpg. How can I directly access this dynamically displayed image?

Is there a way to access this rendered image without having to analyze the source elements myself?

+4
source share
1 answer

There is currentSrcproprety, which is updated only when downloading a candidate. A function might look something like this:

function getCurrentSrc(element, cb){
    var getSrc;
    if(!window.HTMLPictureElement){
        if(window.respimage){
            respimage({elements: [element]});
        } else if(window.picturefill){
            picturefill({elements: [element]});
        }
        cb(element.src);
        return;
    }

    getSrc = function(){
        element.removeEventListener('load', getSrc);
        element.removeEventListener('error', getSrc);
        cb(element.currentSrc);
    };

    element.addEventListener('load', getSrc);
    element.addEventListener('error', getSrc);
    if(element.complete){
        getSrc();
    }
}

Note: you need to pass a imgDOM element and a callback function.

+4
source

Source: https://habr.com/ru/post/1568018/


All Articles