How to prevent background image from flickering when changing
P粉590929392
P粉590929392 2023-10-20 21:38:57
0
2
803

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粉590929392
P粉590929392

reply all(2)
P粉878542459

Preload the image like this without including and display: none

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

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;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template