Store images in Javascript object

前端 未结 3 1449
谎友^
谎友^ 2020-12-04 10:36

I am not sure if this is possible, but I want to store an image in a JavaScript variable or an object and when the page loads, I want to make those images appear where desir

相关标签:
3条回答
  • 2020-12-04 10:46

    You can simply use

    var img = new Image();
    img.src = "http://yourimage.jpg";
    

    to create a DOM image.

    A DOM image is an object in memory that contains the image binary form, so there's no need to convert it back to an image since it's already one.

    0 讨论(0)
  • 2020-12-04 11:03

    It appears that the OP is requesting how to do data islands in JavaScript, specifically for images. None of the answers previously given provide such a method, so here you go.

    Basically, you encode the image as a base64 string and then set that as the source of a DOM element. Setting the source of an Image object to a url is not equivalent, since it requires an addition HTTP connection.

    var data = 'data:image/gif;base64,'+
        'R0lGODlhAAEwAMQAAJ2M5Me98GRK1DoYyYBr3PHv++Pe99XO81Y50auc6PBkZEgpzbmt7HJa2I57'+
                // snip //
        'fS3CqU7XGYgE+GqHvrLJ8Tr6qXmqiwAF9CffgnMNqmWHAWNBwwGsKpKsrmJqltOOV69nuYxSkqpo'+
        'Tata18rWtrr1rTIIAQA7';
    var icon_elem = document.getElementById("icon_here");
    icon_elem.src = data;
    

    The above code and a full example can be found here: http://www.kawa.net/works/js/data-scheme/base64-e.html

    0 讨论(0)
  • 2020-12-04 11:10

    See, this is a simple matter. But the method to approach this problem is not the way you are trying right now.

    What you think will work:
    We'll store the image (its binary data) in a js variable, and then slap it on the page any time.

    How it will work much more easily:
    you just have to create a DOM image on the page, and set its source. The browser will fetch the image from the server automatically.

    Examples:

    ex-1:

    var img_src = "http://someserver/yourimage.png";
    var node = document.getElementById('the-node-in-which-i-want-my-image');
    node.innerHTML = "<img src='"+img_src+"' alt='my image'>";
    

    ex-2: (using jquery) - this is essentially the same as above, only much easier to write:

    var img_src = "http://someserver/yourimage.png";
    $('#the-node-in-which-i-want-my-image')
        .html("<img src='"+img_src+"' alt='my image'>");
    

    Now, there's one more thing: the browser starts fetching the image after this code runs, so the image actually appears a little after you insert it into the DOM.

    To prevent this, you can pre-fetch the images using:

    var prefetch = new Image();
    prefetch.src = "http://someserver/yourimage.png";
    

    Cheers!

    0 讨论(0)
提交回复
热议问题