I've got a sprite of two images, one position is 0 0, another 0 -150 px. I'd like to make them change every 10 seconds. I'm vaguely familiar with JavaScript, so far I've got
this:
function changeBackground () {
// some for loop? //
}
setInterval(function(){changeBackground()},10000);
I'm sorry this is realy just a few lines but I'm really lost. A little hint would be appreciated.
Something like this. This is untested, so there might be some errors, but you could solve it like this:
<div id="sprite"></div>
setBackgroundImage(frameNumber) {
var style = document.getElementById('sprite').style;
var pos;
if (frameNumber === 0) {
pos = 0;
} else if (frameNumber === 1) {
pos = -150;
}
style.backgroundPositionX = pos;
}
var currentFrame = 0;
function changeBackground () {
currentFrame ++;
currentFrame = currentFrame % 2;
setBackgroundImage
}
setInterval(function(){changeBackground()},10000);
Maybe this is help you if you need with animation please comment http://jsfiddle.net/hmZ7W/
var button = document.getElementById("button");
var oddEven = 1;
function changeBackground () {
if(oddEven)
{
button.style.backgroundPosition = "0 150px";
oddEven = 0;
}
else
{
button.style.backgroundPosition = "0 0";
oddEven = 1;
}
}
setInterval(function(){changeBackground()},500);
You may try this code for animation in JS:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
#sprite {
width: 100px;
height: 100px;
background: url(image.jpg) 0 0;
}
</style>
</head>
<body onload="main();">
<script>
var pos = [-10, -20, -30]; // image offset
var posIdx = 0; // offset index
function main() {
var img = document.createElement('img')
img.id = 'sprite';
document.body.appendChild(img);
setInterval(function() {
anim(img);
}, 1000);
}
function anim(el) {
posIdx++;
if (posIdx > pos.length - 1) posIdx = 0;
el.style.backgroundPositionX = pos[posIdx] + 'px';
}
</script>
</body>
this is what i mean...
to support other browsers you need to add the other prefixes.(this works in chrome and safari)
NO javascript needed .. .especially NO timers.
your image is 'sprite.png' width 300px height 150px in this example
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
div{
width:150px;height:150px;
background:url(sprite.png) no-repeat 0px 0px;
-webkit-animation:mymove 10s infinite;
}
#-webkit-keyframes mymove{
0%{background-position:0px 0px;}
50%{background-position:0px 0px;}
51%{background-position:-150px 0px;}
100%{background-position:-150px 0px;}
}
</style>
</head>
<body>
<div></div>
</body>
</html>
another way to don't use the javascript timer... is to change class on transition end.
so 2 classes every transition lasts 10sec.. and on end it swaps class.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
div{
width:150px;height:150px;
background:url(sprite.png) no-repeat 0px 0px;
-webkit-transition:background-position 0s linear 10s;
}
div.odd{
background-position:-150px 0px;
}
</style>
</head>
<script>
window.onload=function(){
var div=document.getElementsByTagName('div')[0];
div.addEventListener('transitionend',function(){
this.classList.toggle('odd');
},false);
div.classList.toggle('odd');// start the transition
}
</script>
<body>
<div></div>
</body>
</html>
Related
I am using this code to simply move a small element(ball here), but the transform translate is only working once, even when the setInterval() function is continuously working?
This is the html file --
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="MoveTheBall.css">
<title>Move the ball</title>
</head>
<body>
<div class="ball"></div>
<script src="MoveTheBall.js"></script>
</body>
</html>
and CSS file--
.ball{
height: 5rem;
width: 5rem;
background-color: salmon;
border-radius: 50%;
position: relative;
top: 35vw;
left: 45vw;
}
and the JavaScript file--
var ball = document.querySelector('.ball');
document.addEventListener('keypress' , function(event) {
console.log('key', event.key);
if(event.key === 'w') {
moveUp();
}
});
function moveUp() {
let ballRect;
let interval = setInterval(function() {
ballRect = ball.getBoundingClientRect();
if(ballRect.top > 0) {
ball.style.transform = 'translateY(-10px)';
} else {
clearInterval(interval);
}
}, 300);
}
Here I was expecting to move the ball up until it reaches to the top of the screen after pressing w key. But the ball is only moving only once.
function moveUp() {
let ballRect;
let interval = setInterval(function() {
ballRect = ball.getBoundingClientRect();
if(ballRect.top > 0) {
let currentTop = parseFloat(getComputedStyle(ball).getPropertyValue('top'));
ball.style.transform = `translateY(${currentTop - 10}px)`;
} else {
clearInterval(interval);
}
}, 300);
}
How come my div is not printing for as many times as it loops?
I want the picture to be displayed 10 times and for some reason is is only showing up twice. Any ideas, all help is welcome and appreciated. Thanks!
I select the Div, I clone it, and now I want to display it 10 times.
var stuffIWantRepeated = document.getElementsByTagName("DIV")[0];
var clone = stuffIWantRepeated.cloneNode(true);
for (var i = 1; i <= 10; i++) {
document.body.appendChild(clone);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#maindiv img {
border-bottom-color: black;
display: block;
margin-left: auto;
margin-right: auto;
}
#maindiv {
padding-top: 10%;
}
</style>
</head>
<body>
<div id="maindiv">
<img src="https://pbs.twimg.com/profile_images/571024672750178304/GpGC8aTW.jpeg" border="40">
</div>
</body>
</html>
You have to clone once for each time you want to append it. A particular node can only be in the DOM in one place.
Just move that line into the loop:
for(var i = 1; i <= 10; i++) {
var clone = stuffIWantRepeated.cloneNode(true);
document.body.appendChild(clone);
}
!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#maindiv img {
border-bottom-color: black;
display: block;
margin-left: auto;
margin-right: auto;
}
#maindiv {
padding-top: 10%;
}
</style>
</head>
<body>
<div id="maindiv">
<img src="https://pbs.twimg.com/profile_images/571024672750178304/GpGC8aTW.jpeg" border="40">
</div>
</body>
<script>
var stuffIWantRepeated = document.getElementsByTagName("DIV")[0];
for (var i = 1; i <= 10; i++) {
var clone = stuffIWantRepeated.cloneNode(true);
document.body.appendChild(clone);
}
</script>
</html>
Rather than creating a clone and appending it ten times over, you should create ten clones and append each individually:
Replace:
<script>
var stuffIWantRepeated = document.getElementsByTagName("DIV")[0];
var clone = stuffIWantRepeated.cloneNode(true);
for(var i = 1; i <= 10; i++) {
document.body.appendChild(clone);
}
</script>
With this:
<script>
var stuffIWantRepeated = document.getElementsByTagName("DIV")[0];
for(var i = 1; i <= 10; i++) {
var clone = stuffIWantRepeated.cloneNode(true);
document.body.appendChild(clone);
}
</script>
For example: https://jsfiddle.net/40wukrta/
You need to clone it every time in your loop. Once appended into the document, the clone will get invalid.
var stuffIWantRepeated = document.querySelectorAll("DIV")[0];
for (var i = 1; i <= 10; i++) {
var clone = stuffIWantRepeated.cloneNode(true);
document.body.appendChild(clone);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#maindiv img {
border-bottom-color: black;
display: block;
margin-left: auto;
margin-right: auto;
}
#maindiv {
padding-top: 10%;
}
</style>
</head>
<body>
<div id="maindiv">
<img src="https://pbs.twimg.com/profile_images/571024672750178304/GpGC8aTW.jpeg" border="40">
</div>
</body>
</html>
I want to create a text that can be shifted for long title.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
#abc {
position: relative;
overflow: hidden;
width: 200px;
height: 100px;
}
#def {
position: absolute;
font-size: 2em;
color: #000;
margin: 0;
width: 400px;
}
</style>
<script>
var teks = null;
function geser() {
var left = 0;
function frame() {
left--; // update parameter
teks.style.left = left + 'px';
if (left == -200) {
clearInterval(id);
setTimeout(function() {
runningtext();
}, 2000);
}
}
var id = setInterval(frame, 40)
}
function runningtext() {
teks = document.getElementById("def");
teks.style.left = '0px';
setTimeout(function() {
geser();
}, 2000);
}
window.onload = runningtext;
</script>
</head>
<body>
<div id="abc">
<p id="def">Cihampelas Demin Center</p>
</div>
</body>
</html>
The script is successfully work with 1 line.
Output :
Cihampelas Demin Center
Question is :
Is there another way to print 1 line without #def { width:400px; }?
(When I try #def { display:inline; }
Output :
Cihampelas
Demin Center
)
When object's left = -200px, I want to reserve in same way, but I have no idea.
I want to move my background infinite, to do that i code this :
html, body {
margin : 0;
padding: 0;
width: 100%;
height: 100%;
cursor: url('../assets/img/ship.cur'), auto;
background-color : #000;
}
#background {
position : absolute;
background-image: url('../assets/img/littlestars.png');
height : 720px;
width : 1280px;
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" href="../style/home.css">
<script language=javascript src="../js/navigate.js"> </script>
<script language=javascript src="../js/background.js"> </script>
</head>
<body onLoad="onLoad(); loadBG();">
<div id="background"> </div>
</body>
</html>
function loadBG() {
window.setInterval(moveStars, 100);
}
function moveStars() {
var bg = document.getElementById("background");
bg.style.backgroundPosition += 10;
}
But it doesn't work... if i can't display backgroundPosition.
Some ideas ? It's the good way to create javascript animation ? Thx.
backgroundPosition is a property that indicates x,y position of backrogund in units, not a single number.
You need to do something like:
var posx = 0;
function moveStars() {
var bg = document.getElementById("background");
posx+=10;
bg.style.backgroundPosition = posx+"px 0";
}
Here simple code1 which work fine Demo jsFiddle ,I want the same result in code2
Here the code2 Demo jsfiddle which have two problems.
The scale is not correct to 1400x700 pix
I can only successes to draw from inside function loadImage()
function loadImage(){
oG.width = 1400;
oG.height = 700;
oG.drawImage(scrollImg,0,0);
}
I want to draw from scrollObject.draw()
var scrollObject = {
draw : function() {
oG.drawImage(scrollImg,0,0);
}
};
How can I do that ?
Many thanks.
code1;
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#mycanvas{
border: 1px solid #9C9898;
}
</style>
</head>
<body >
<canvas id="mycanvas" width="1400" height="700" ></canvas>
<script type="text/javascript">
// get the canvas element using the DOM http://jsfiddle.net/centerwow/Z2UzF/show/
var context = document.getElementById('mycanvas').getContext("2d");
context.width = 1400 ;
context.height = 700 ;
var img = new Image();
img.src = "http://s9.postimage.org/433ecr79b/grid.png";
img.onload = function () {
context.clearRect(0,0,1400,700);
context.drawImage(img, 0, 0);
}
</script>
</body>
</html>
code2:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> image not display correct</title>
<style type='text/css'>
body {
background-color:black;
}
.Container {
position: relative;
margin-left:auto;
margin-right:auto;
top:10px;
background-image:url('http://s8.postimage.org/jnu65wk2d/Box_Grass200x100.jpg');
background-repeat:repeat;
width:1000px;
height:500px;
z-index:0;
overflow:hidden;
}
#layer1{
position:absolute;
padding:0;
margin: 0px;
z-index:2;
top:-100px;
left:-200px;
width:1400px;
height:700px;
}
</style>
</head>
<body >
<div class="Container">
<canvas id="layer1">LAYER1</canvas>
</div>
<script type='text/javascript'>//http://jsfiddle.net/centerwow/Z2UzF/1/show/
function loadImage(){
oG.width = 1400;
oG.height = 700;
oG.drawImage(scrollImg,0,0);
}
//layer 1 image then will be object objectGame = oG
var oG = document.getElementById('layer1').getContext("2d");
scrollImg = new Image();
scrollImg.src = "http://s9.postimage.org/433ecr79b/grid.png"; //image size 1400x700px
scrollImg.onload = loadImage;
var scrollObject = {
// Basic attributes
draw : function() {
oG.drawImage(scrollImg,0,0);
}
};
// Now moving it
function move() {
//handle with object background
//clearRect(x, y, width, height)
oG.clearRect(0,0,1400,700);
scrollObject.draw();
}
move();
</script>
</body>
</html>
You can only draw on loadImage(), because when you trigger move() the image have not been loaded yet. You can use a assetmanager to download your assets like images, sounds etc. Here is a great guide to build one - http://www.html5rocks.com/en/tutorials/games/assetmanager/
And for the scale, you can pass a width and height argument to the drawImage function.
context.drawImage(image, x, y, width, height);
You are also setting the height and width of the 2d-context, that you cannot do. Set the width and height in the <canvas> attributes. I once had problems with height/width when I used css, so I would not recommend setting the width/height there.