如何防止背景图像在变化时闪烁 [英] How to prevent a background image flickering on change

查看:196
本文介绍了如何防止背景图像在变化时闪烁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过javascript将如此重复的背景图片从画布应用到div:

I'm applying a repeated background image from a canvas to a 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 + ')';

我必须频繁更新。问题是,它改变时闪烁,它似乎不发生在Chrome,但它在Firefox和Safari真的很糟糕。是否可以停止这个?

I have to update it quite frequently. The problem is it flickers upon change, it doesn't appear to happen in Chrome but it's really bad in Firefox and Safari. Is it possible to stop this? I didn't think it would happen since it's a dataurl and therefore doesn't need to be downloaded.

解决方案:

// 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;


推荐答案

尝试将图片预加载到设备存储在dom中的图像像下面的HTML代码。也许错误出现,因为图像资源需要加载,需要一些时间(闪烁)。

Try to preload the image to the device storage by include the image in the dom like in the following HTML-Code. Maybe the error comes up cause the image resource need to be loaded which takes some time (flickering).

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

您可能希望使用 sprites-images 。通过使用sprite,您的应用程序将需要更少的HTTP请求来加载所有资源到您的页面。如果使用 css animations ,请添加以下CSS样式。它将防止移动设备上的背景闪烁:

You may prefer to use sprites-images. By using sprites your application will need less HTTP-Requests to load all ressources into your page. Also add the following CSS styles if you are using css animations. It will prevent background flickering on mobile devices:

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

这篇关于如何防止背景图像在变化时闪烁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆