search

Home  >  Q&A  >  body text

How to prevent background image from flickering when changing

I applied a repeating background image from the canvas to the div via JavaScript like this:

var img_canvas = document.createElement('canvas');

img_canvas.width = 16;

img_canvas.height = 16;

img_canvas.getContext('2d').drawImage(canvas, 0, 0, 16, 16);

var img = img_canvas.toDataURL("image/png");

document.querySelector('#div').style.backgroundImage = 'url(' + img + ')';

I have to update it frequently. The problem is that it flickers on change, which doesn't seem to happen in Chrome, but is really bad in Firefox and Safari. Is it possible to prevent this? I don't think this is happening since it is a dataurl and therefore does not need to be downloaded.

solution:

// create a new Image object
var img_tag = new Image();

// when preload is complete, apply the image to the div
img_tag.onload = function() {

    document.querySelector('#div').style.backgroundImage = 'url(' + img + ')';
}

// setting 'src' actually starts the preload
img_tag.src = img;


P粉590929392P粉590929392459 days ago833

reply all(2)I'll reply

  • P粉878542459

    P粉8785424592023-10-21 16:14:30

    Preload the image like this without including and display: none

    <link rel="preload" href="/images/bg-min.png" as="image">

    reply
    0
  • P粉364642019

    P粉3646420192023-10-21 12:01:11

    Attempt to preload image resources into device storage by including the image in the DOM, as shown in the following HTML code. The error may occur because the image resource needs to be loaded, which takes some time (flickering).

    <img src="imageToPreload.png" style="display:none;" alt="" />

    You may prefer to use sprites-images. By using sprites, your application will require fewer HTTP requests to load all resources into your page. If you use css animation, please also add the following CSS styles. It will prevent background flickering on mobile devices:

    -webkit-backface-visibility: hidden;
    -moz-backface-visibility:    hidden;
    -ms-backface-visibility:     hidden;

    reply
    0
  • Cancelreply