How to display a constantly changing image file in a browser without refresh flicker?

前端 未结 3 1982
南旧
南旧 2021-02-05 12:56

I\'m displaying an image (from a file) on the browser using html... I have another program that keeps taking a screenshot of my screen and storing it as an image file \"image.jp

3条回答
  •  爱一瞬间的悲伤
    2021-02-05 13:28

    First, when you set the src attribute of your image object, the image has not been loaded yet, you need to refresh your canvas when the onload of the image gets fired (when the image is done loading).

    Secondly, the browser tries to use the cached image image.jpeg. To avoid that, add a bogus argument to the image URI.

    For example :

    var timeoutPeriod = 1000;
    var imageURI = 'image.jpeg';
    var x=0, y=0;
    var img = new Image();
    img.onload = function() {
        var canvas = document.getElementById("x");
        var context = canvas.getContext("2d");
    
        context.drawImage(img, x, y);
        x+=20; y+=20;
        setTimeout(timedRefresh,timeoutPeriod);
    };
    
    function timedRefresh() {
        // just change src attribute, will always trigger the onload callback
        img.src = imageURI + '?d=' + Date.now();
    }
    

    And then it should work.

提交回复
热议问题