Try th开发者_JAVA技巧e following link in any web browser on your desktop and then try it on any mobile browser (tried it on Android, iPhone & iPad - all produce same problem) and can someone tell me why the first 'frame' (well original sprite position) is always displayed behind the animation?
http://24hours-in.lincoln.ac.uk/projects/mus/animate2.html
Thanks!
Solved it! (with a fudge)
var character = null;
var xOffset = 0;
function animate() {
if(xOffset < 360){
xOffset += 30;
} else {
xOffset = 0;
}
character = document.getElementById("character");
character.style.backgroundImage = "url('char2.png')";
character.style.backgroundPosition = xOffset + "px 0px";
setTimeout(animate,250);
}
function init() {
var character = document.createElement("div");
character.id = "character";
character.style.backgroundImage = "url('spacer.png')";
character.style.position = "absolute";
character.style.width = "30px";
character.style.height = "65px";
document.getElementById("stage").appendChild(character);
animate();
}
window.onload = init;
I figured it was using a background fallback of the original image because of the transparency. Therefore, instead of starting off with the background image, I started off by applying a 1px transparent PNG file (abut assigning the rest of the CSS ready for the char PNG) and when it comes to the animation, I then substitute the background image to the char.PNG version.
I am sure there are more elegant ways, but this does the job!
You know, to be honest, I don't know what causes the issue, but the issue is that the character
background-image is static - that is to say, it's set in stone (via css).
A fix around your issue is to dynamically add the background-image using javascript. Here's your revised code.
CSS
<style type="text/css">
body {
padding: 0px;
margin: 0px;
}
#character {
position:absolute;
width:30px;
height:65px;
background-position: center center;
overflow: hidden;
}
</style>
Javascript
<script type="text/javascript">
var character = null;
var xOffset = 0;
function animate() {
if(xOffset < 360){
xOffset += 30;
} else {
xOffset = 0;
}
character.style.backgroundImage = "url('char.png')";
character.style.backgroundPosition = xOffset + 'px, 0px';
setTimeout(animate,250);
}
function init() {
character = document.getElementById("character");
animate();
}
window.onload = init;
</script>
HTML
<body>
<div id="character"></div>
</body>
精彩评论