Home > other >  JavaScript Refresh page and set image width and height of Source(blob)
JavaScript Refresh page and set image width and height of Source(blob)

Time:10-05

I would like to know please

  1. How to Refresh var xhr = new XMLHttpRequest();
  2. and set the width and height of blob

It's from a App that sends a Base64String Image(WebCam)

I would like to Refresh portion of the page to get the new Image. It works manually ...

<!DOCTYPE html>
<html>
<body>
<img id="photo" width="400" height="400"/>

<script>
var xhr = new XMLHttpRequest();
xhr.open( "GET", "http://192.168.1.186:8080/dwkpic.html", true );
xhr.responseType = "arraybuffer";
xhr.onload = function( e ) {
    var arrayBufferView = new Uint8Array( this.response );
    var blob = new Blob( [ arrayBufferView ], { type: "image/jpeg" } );
    var urlCreator = window.URL || window.webkitURL;
    var imageUrl = urlCreator.createObjectURL( blob );
    var img = document.querySelector( "#photo" );
    img.src = imageUrl;
};
xhr.send();
</script>
</body>
</html>

I have tried setTimeout()

<!DOCTYPE html>
<html>
<body>
<img id="photo" width="400" height="400"/>
<script>
setTimeout(function(){
var xhr = new XMLHttpRequest();
xhr.open( "GET", "http://192.168.1.186:8080/dwkpic.html", true );
xhr.responseType = "arraybuffer";
xhr.onload = function( e ) {
    var arrayBufferView = new Uint8Array( this.response );
    var blob = new Blob( [ arrayBufferView ], { type: "image/jpeg" } );
    var urlCreator = window.URL || window.webkitURL;
    var imageUrl = urlCreator.createObjectURL( blob );
    var img = document.querySelector( "#photo" );
    img.src = imageUrl;
img.width="400";
img.height="400";
};
xhr.send();
}, 10);
</script>
</body>
</html>

Thanks

CodePudding user response:

if you want to run the function periodically, you just have to use setInterval instead of timeout.


setInterval(function(){
var xhr = new XMLHttpRequest();
xhr.open( "GET", "http://192.168.1.186:8080/dwkpic.html", true );
xhr.responseType = "arraybuffer";
xhr.onload = function( e ) {
    var arrayBufferView = new Uint8Array( this.response );
    var blob = new Blob( [ arrayBufferView ], { type: "image/jpeg" } );
    var urlCreator = window.URL || window.webkitURL;
    var imageUrl = urlCreator.createObjectURL( blob );
    var img = document.querySelector( "#photo" );
    img.src = imageUrl;
img.width="400";
img.height="400";
};
xhr.send();
}, 10);

but keep in mind, this approach will make 100 requests per second which is a lot of requests. So it is possible that browser might get overloaded.

I think what you want to do is actually streaming data, so you can maybe look at at how to stream data to browser.I don't know if you control the backend but if you do, you can also pipe the data.

  • Related