简体   繁体   English

通过socket.io事件设置后如何更改图像src?

[英]How to change image src after set by socket.io event?

Using socket.io, I'm pushing images from a server to the client using base64 encoded strings: 使用socket.io,我使用base64编码的字符串将图像从服务器推送到客户端:

socket.on('send_picture', function (data){
    socket_data = (socket_data + data);
    document.getElementById('imgid').src = socket_data
})

How can I reset the src of 'imgid' at the next socket.io event? 如何在下一个socket.io事件中重置'imgid'的src? It works fine one time, but then won't display new images until I refresh the page 一次可以正常工作,但是直到我刷新页面后才显示新图像

I've found that the most reliable way to load new image content is to create a new image element each time and replace the prior image object with the new one. 我发现,加载新图像内容的最可靠方法是每次创建一个新的图像元素,然后用新的图像对象替换以前的图像对象。 You could do that like this: 您可以这样做:

socket.on('send_picture', function (data){
    socket_data = socket_data + data;
    var oldImg = document.getElementById('imgid');
    var newImg = new Image();
    newImg.src = socket_data;
    newImg.id = 'imgid';
    oldImg.parentNode.replaceChild(newImg, oldImg);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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