Store images in Javascript object

前端 未结 3 1462
谎友^
谎友^ 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 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

提交回复
热议问题