Adding a background image under a background color function - javascript

I have the three functions running on my interactive pet (change background, dimmer lights, mouse follow). I'm trying to add an image to the background of the body, but every time I try it gets pushed to the top and the dirty/clean tank function doesn't work. Could someone tell me how to change the color sections of the first function below to switch between images instead of color codes? I think that would solve the immediate problem. :/
CSS Code:
//change background color: dirty/clean tank
setTimeout(function dirty() { //sets background color to murky green
document.body.style.backgroundColor = ****"#CCCC99";** //would like this to be an image**
var btn = document.body.appendChild(document.createElement('button'));
btn.appendChild(document.createTextNode("Clean the tank!"));
document.body.style.marginTop = "-1000px";
btn.onclick = function clean() {
btn.parentNode.removeChild(btn);
document.body.style.backgroundColor = **"#CCFFFF";//would like this to be an image**
setTimeout(dirty,27000); //how long it takes to make the tank dirty
};
},500); //first loading of clear blue timeout
//dim the lights
var dimmed = 0;
function toggleLights()
{
var dimmer = document.getElementById("dimmer");
if(dimmed == 0) dimmed = 1;
else dimmed = 0;
if(dimmed == 1)
{
dimmer.style.opacity = 0.8;
dimmer.style.visibility = "visible";
}
if(dimmed == 0)
{
dimmer.style.opacity = 0.0;
dimmer.style.visibility = "hidden";
}
}
//fish moves on mouse hover
$(document).ready(function() {
$("#swim").mousemove(function (event) {
var fish = $("#fish1");
var position = fish.position();
var mousey = event.pageX;
if (position.left > mousey) {
$("#fish1").html("<img src='images/happy.png' />");
} else {
$("#fish1").html("<img src='images/happyback.png'/>");
}
$("#fish1").stop().animate({
left: event.pageX,
top: event.pageY
}, 300);
});
});
HTML Code:
<HTML>
<HEAD>
<TITLE>Untitled</TITLE>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"
</script>
<script type="text/javascript" src="pet.js"></script>
<script type="text/javascript" src="core.js"></script>
</HEAD>
<div id="table">
<div id="dimmer" onClick="toggleLights()"></div>
<a href="javascript:toggleLights();"><img src="images/table-lamp.png" height="380px"
alt="table lamp"></a>
</div>
<div id="swim">
<div id="fish1"><img src="images/happy.png"/></div>
</div>
</BODY>
</HTML>

Add a starting <body> tag in your HTML, and change element classes with javascript, instead of style properties. That way you have more control over the styling through your CSS file.
So you would do something like:
document.body.className = 'state1';
And in your CSS
.state1{
background-image: url(the/image.jpg);
}
and so on...

Related

How to flip an image in javascript on a html canvas?

I am making a game in pure js with an HTML5 canvas. My player is a cube but its weapons are images. I have successfully drawn the image on top of the player:
var gun = document.getElementById('gun');
c.drawImage(gun,this.x,this.y);
but I want it to flip the gun image vertically when the player turns. I have tried changing scaleX when the player turns:
if(this.l == true){
this.x -= this.speed;
gun.style.transform = 'scaleX(-1)';
}
if(this.r == true){
this.x += this.speed;
gun.style.transform = 'scaleX(1)';
}
but nothing happens, please help
the HTML :
<html>
<head>
<title>CUBE</title>
<style>
body{
margin: 0px;
}
</style>
<link rel="shortcut icon" type="image/ico" href="favicon.ico"/>
</head>
<body>
<canvas id='canvas'></canvas>
<img id="gun" style ='display: none;' src="gun.png">
<script src = 'index.js'></script>
</body>
Instead of using css for scaling I would go for the following solution:
function goLeft() {
gun.flipX = true
}
function goRight() {
gun.flipX = false
}
function drawGun() {
if(gun.flipX) {
ctx.drawImage(gunImg, -gun.x -gun.w,gun.y,gun.w,gun.h)
}
else {
ctx.drawImage(gunImg,gun.x,gun.y,gun.w,gun.h)
}
}

How can i call setInterval more than one time?

So, i want to call setInterval with a button multiple times, but when i press the button a second time nothing happens. I have searched for other similar questions but they are in jQuery and dont worked for me.
Edit: What i wan't to do is to repeat the animation by clicking the button.
var element, add, intervalo;
add = 0;
function start(){
intervalo = setInterval(interval, 50);
}
function interval() {
add = add + 25;
element = document.getElementById('teste');
element.style.left = add;
if (add > 300) {
clearInterval(intervalo);
intervalo = null;
element.style.left = 0;
}
}
#teste {
position: absolute;
}
<html>
<head>
<script src="js/main.js"></script>
<link rel="stylesheet" src="text/css" href="css/estilo.css">
</head>
<body>
<h1 id="teste">Ola</h1>
<button onclick="start()">Start</button>
</body>
</html>
You are not resetting your add variable so when the interval is triggered a second time it will go right to the clearInterval section.
var element, add, intervalo, btn, element;
add = 0;
btn = document.getElementById('btn');
element = document.getElementById('teste');
function start() {
btn.disabled = true;
intervalo = setInterval(interval, 50);
}
function interval() {
add = add + 25;
element.style.left = add + 'px';
if (add > 300) {
clearInterval(intervalo);
intervalo = null;
element.style.left = 0;
btn.disabled = false;
add = 0;
}
}
#teste {
position: absolute;
left: 0;
top: 0;
}
<html>
<head>
<script src="js/main.js"></script>
<link rel="stylesheet" src="text/css" href="css/estilo.css">
</head>
<body>
<h1 id="teste">Ola</h1>
<button id="btn" onclick="start()">Start</button>
</body>
</html>

onClick event on image while already moving

I'm trying to make an image that moves to the right on my website. When you click the image, it should move to the left. For now, this doesn't happen, any ideas? If possible, in pure Javascript and no Jquery ;)
Also, if you click the image for a second time, it should move to the right again. Every consecutive time, the image should move to the other side. I guess this would be best with a for-loop?
<script type"text/javascript">
window.onload = init;
var winWidth = window.innerWidth - movingblockobject.scrollWidth; //get width of window
var movingblock = null //object
movingblock.onclick = moveBlockLeft();
function init() {
movingblock = document.getElementById('movingblockobject'); //get object
movingblock.style.left = '0px'; //initial position
moveBlockRight(); //start animiation
}
function moveBlockRight() {
if (parseInt(movingblock.style.left) < winWidth) { // stop function if element touches max window width
movingblock.style.left = parseInt(movingblock.style.left) + 10 + 'px'; //move right by 10px
setTimeout(moveBlockRight,20); //call moveBlockRight in 20 msec
} else {
return;
}
}
function moveBlockLeft () {
movingblock.style.right = parseInt(movingblock.style.right) + 10 + 'px'
}
</script>
Please first go through the Basics of javascript before trying out something .
window.onload = init;
var winWidth = window.innerWidth;
var movingblock = null;
var intervalid = null;
var isLeft = false;
function init() {
console.log('Init');
movingblock = document.getElementById('movingblockobject');
movingblock.style.left = '0px';
intervalid = setInterval(function() {
moveBlock(true);
}, 2000);
movingblock.onclick = function() {
moveBlock(false);
};
}
function moveBlock(isSetInterval) {
if (!isSetInterval)
isLeft = !isLeft;
if (parseInt(movingblock.style.left) < winWidth) {
if (isLeft)
movingblock.style.left = parseInt(movingblock.style.left) - 10 + 'px';
else
movingblock.style.left = parseInt(movingblock.style.left) + 10 + 'px';
} else {
movingblock.style.left = '0px';
}
}
function moveBlockLeft() {
clearInterval(intervalid);
movingblock.style.right = parseInt(movingblock.style.right) + 10 + 'px';
intervalid = setInterval(moveBlockRight, 20);
}
<div id="movingblockobject" style="width:50px;height:50px;border:solid;position: absolute;">
var movingblock = null
this are mistakes you have delclared it as null and next line you are binding click event.Also for assigning click event you should assign the name of the function.
movingblock.onclick = moveBlockLeft;
above is basic bug there are lot like the above.I feel Self learning is much better for basics
try yourself.
try the above it will work but please try yourself
You should CSS3 transition, works like a charm. Just toggle a class "right"
HTML:
<html>
<head>
<style>
#movingblockobject{
width: 40px;
padding: 10px;
position: fixed;
height:10px;
left:0px;
-webkit-transition: left 2s; /* For Safari 3.1 to 6.0 */
transition: left 2s;
}
#movingblockobject.right{
left:200px;
}
</style>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$( document ).ready(function() {
$('#movingblockobject').on('click', function (e) {
$('#movingblockobject').toggleClass("right");
});
});
</script>
</head>
<body>
<div id="movingblockobject" class="demo">add image here</div>
</body>
</html>

Simple javascript html image game

I have a simple game where image moves randomly and score increases when user clicks on it.
The first image displays before game is started, which when clicked calls the play() function in javascript, which hides that image and displays the image that is to be used for the game.
That is where my code is stuck, it does not call the function play(). I am new to javascript and html. Any help would be great!
Here is my code
<html>
<head>
<title>Image click Game!</title>
<script>
global var score = 0;
global var left=400;
global var top = 100;
function play() {
var game = document.getElementById('game');
var firstDiv = document.getElementById('firstDiv');
var height = window.innerHeight;
var width = window.innerWidth;
firstDiv.style = 'display : none';
game.style='display : block';
setInterval("move()", 1000);
}
function move() {
var randomNumberX = Math.floor(Math.random()*11)-5;
var randomNumberY = Math.floor(Math.random()*11)-5;
left = left + randomNumberX;
top = top+randomNumberY;
var im = document.getElementById('image');
im.style.left = left;
im.style.top = top;
}
</script>
</head>
<body>
<div id ="firstDiv" style="display : block">
<img src="pics/playgame.gif" width="108" height="106" onClick = "play()"/></a>
</div>
<div id="game" style="display : none">
<p>"Score: " + score</p>
<img id="image" src="pics/gameImage.gif" onClick = "score++" style="position:absolute; left: 400; top: 100;"/></a>
</div>
</body>
</html>
There are a handful of things wrong with your code:
1) Your <img> tags are ended with a stray, unneeded </a> tag.
2) In your <img> tag, you should change to onClick = "play();"
3) I don't believe javascript supports the global keyword in that way.
4) To change CSS style, try this:
firstDiv.style.display = 'none';
game.style.display = 'block';
5) You cannot display javascript variables in this fashion: <p>"Score: " + score</p>...not to mention there is no declared variable 'score' to begin with!
Keep working at it, you only get better with practice.
Tyr this
<script>
var score = 0;
var left=400;
var top = 100;
function play() {
var game = document.getElementById('game');
var firstDiv = document.getElementById('firstDiv');
var height = window.innerHeight;
var width = window.innerWidth;
firstDiv.style.display='none';
game.style.display='block';
setInterval("move()", 1000);
}
function move() {
var randomNumberX=Math.floor(Math.random()*11)-5;
var randomNumberY=Math.floor(Math.random()*11)-5;
left= left+randomNumberX;
top = top+randomNumberY;
var im= document.getElementById('image');
im.style.left=left;
im.style.top=top;
}

coding 2D game physics in javascript, not-flat ground and rotation

I have a small project in my webprogramming course where I am supposed to make a small game in javascript. This is the game: two cannons are fixed on
opposing ends of the game space. The cannons take turns shooting at each other, and the player tilts the cannon to some degree and chooses a force to shoot the cannonball with. There's a bunch of other stuff I'm thinking of that will be added if there's time.
I found a nice site, http://www.rodedev.com/tutorials/gamephysics/, to get me going with 2d physics and I've made some tests, see the code below. I do however have two big problems:
Non-flat floor/ground.
Rotation!
Right now the script is only checking for the style.top value of the floorDiv, so the box will always "land" on this row of pixels. If I want to have
variable-height terrain, this won't suffice. Any ideas from you guys on how this could be accomplished? Is there anyway to check the color at a specific pixel? If so I could check for non-sky or ground colored pixels and make this the landing critera.
I need to rotate the cannon so players can adjust their aim! I'm thinking I'll make two different cannon objects, the cannon "base" and the cannon barrel. Then I could just rotate the cannon barrel when the player presses a key. Unfortunately rotation seems to be hard in webprogramming. I found this jquery plugin, at http://code.google.com/p/jquery-rotate/, but I'm not getting it to work quite as I would like. Even though I've made sure the cannonball is centered in the picture there is also some translation, not just rotation.
I suppose this might be because the picture doesn't rotate about it's center? See the rotation test code below (you'll have to download
the rotation plugin if you want to try the code).
I suppose I could just make a picture for each angle but that seems kind of wasteful
since there's no actual visual change to the cannon otherwise.
Also, if I want to animate several objects at the same time, do you think I should just change all the objects in the same gameloop function?
Any ideas on this?
The following is the code for the physics-testing
CSS-file
#moveDiv {
position:absolute;
width:100px;
height:100px;
background-color:#000;
}
#floorDiv {
position:absolute;
width:800px;
height:1px;
background-color:#2E2;
}
table {
text-align:right;
}
table input {
width:35px;
}
HTML-file
<script type="text/javascript">
//global vars
var gravity = 0.5;
var friction = 0.5;
var moving = false;
var moveDiv;
var floorDiv;
var yPos;
var xPos;
var floorPos;
var velocity_y = 0;
var velocity_x = 0;
</script>
</head>
<body onload="initialize();">
<input type="button" value="fall" onclick="fall();"></button>
<input type="button" value="Push" onclick="push();"></button>
<input type="button" value="reset" onclick="reset();"></button>
<table>
<tr>
<td>Angle: <input type="text" value="45" id="angle" /></td>
<td>Speed: <input type="text" value="10" id="speed"/></td>
</tr>
<tr>
<td>Gravity: <input type="text" value="0.5" id="gravity" /></td>
<td>Friction: <input type="text" value="0.5" id="friction" /></td>
</table>
<div id="moveDiv"></div>
<div id="floorDiv"></div>
</body>
</html>
js-file
function initialize() {
moveDiv = document.getElementById('moveDiv');
floorDiv = document.getElementById('floorDiv');
moveDiv.style.left=400;
moveDiv.style.top=50;
floorDiv.style.left=200;
floorDiv.style.top=400;
}//end initialize
function fall()
{
moving=true;
var angle = 275;
var rad = angle / (Math.pi * 2);
var scale_x = Math.cos(rad);
var scale_y = Math.sin(rad);
var moveDivSpeed = 0;
gameLoop();
}//end fall
function push()
{
moving=true;
var angle = document.getElementById('angle').value;
var rad = angle / (Math.PI * 2);
var scale_x = Math.cos(rad);
var scale_y = Math.sin(rad);
var moveDivSpeed = document.getElementById('speed').value;
friction = document.getElementById('friction').value;
gravity = document.getElementById('gravity').value;
velocity_x = moveDivSpeed*scale_x;
console.log("original velocity_x is " + velocity_x);
velocity_y = moveDivSpeed*scale_y;
gameLoop();
}
function gameLoop () {
//console.log("gameLoop start");
var len = moveDiv.style.top.length;
var presentTop = parseInt(moveDiv.style.top.substr(0, len-2));
var lenX = moveDiv.style.left.length;
var presentLeft = parseInt(moveDiv.style.left.substr(0, lenX-2));
var len2 = floorDiv.style.top.length;
var floorTop = parseInt(floorDiv.style.top.substr(0, len2-2));
if (moving == true)
{
velocity_y -= gravity;
if ((presentTop+100) - velocity_y < floorTop)
{ //if moveDiv hasn't hit the floor yet...
moveDiv.style.top = presentTop - velocity_y;
moveDiv.style.left = presentLeft + velocity_x;
}
else if (presentTop + 100 == floorTop) //if moveDiv is ON the floor
{
velocity_x = velocity_x*(1-friction);
moveDiv.style.left = presentLeft + velocity_x;
console.log("on the floor");
console.log("friction is " + friction);
console.log(" and velocity_x is " + velocity_x);
console.log("moveDiv.style.left is " +moveDiv.style.left);
if (velocity_x <= 1)
{
console.log("stopped moving");
moving = false;
}
}
else //if moveDiv will hit the floor/go through the floor this time
{
var diff = floorTop - (presentTop + 100);
moveDiv.style.top = presentTop + diff;
moveDiv.style.left = presentLeft + velocity_x;
}
}
else if (moving == false)
{
clearTimeout(runAgain);
console.log("else if moving == false");
return false;
}
var runAgain = setTimeout("gameLoop()", 5);
//console.log("end of gameLoop");
return false;
}//end gameLoop
function reset () {
moving = false;
moveDiv.style.left=400;
moveDiv.style.top=50;
floorDiv.style.left=200;
floorDiv.style.top=400;
}//end reset
Code for the rotation-test(just the html file and the rotation plugin)
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.rotate.1-1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#hide").click(function() {
$("p").hide(500);
$(".box").animate({height:300, opacity:0}, 1000);
});
$("#show").click(function() {
$("p").show(500);
$(".box").animate({height:100, opacity:100}, 1000);
});
$(".box").mouseenter(function() {
$(".box").animate({height:300, opacity:0}, 500);
});
$(".box").mouseleave(function() {
$(".box").animate({height:100, opacity:10}, 1000);
});
$("#move").click(function() {
$("#grey").animate({left: -300, top: -100}, 1000)
.animate({left: -600, top: 200}, 1000);
});
$("#cannonball").click(function() {
$("#cannonball").animate({"left": "+=300", "top": "-=100"}, 500)
.animate({"left": "+=300", "top": "+=100"}, 500);
});
$("p.fading").css("opacity","0.3");
$("p.fading").hover(function() {
$(this).stop().animate({opacity: 1.0}, "slow");},
function () {
$(this).stop().animate({opacity: 0.3}, "slow");
});
$("#rotateRight").click(function() {
$("#cannonball").rotate(10);
});
}); //end jquery document.ready scripts
function initialize () {
document.getElementById('box').style.top = 250;
}
</script>
<style type="text/css">
body {
background-color: #ccc;
}
.box {
background-color: #000;
width:100px;
height:100px;
margin-left:300px;
}
.divMove {
position:relative;
top:350px;
float:right;
background-color: #ddd;
width:100px;
height:100px;
margin-right:100px;
}
#cannonball {
position: relative;
}
</style>
</head>
<body onload="initialize();">
<p>Let's make this disappear and appear.</p>
<button id="hide">Hide</button>
<button id="show">Show</button>
<button id="move">Move</button>
<button id="rotateRight">Rotate+</button>
<div id="box" class="box">
</div>
<div class="divMove" id="grey">
</div>
<img src="http://dl.dropbox.com/u/18833130/Webprogrammering/test/cannonball.png" id="cannonball" border="1" />
<p class="fading">This is a paragraph that fades. Let's see how it looks.</p>
</body>
</html>
I apologize for the long post and the amount of code, but if you want to try it you can basically just copy-paste, and I thought it would be easier to discuss this way!
I'm thinking I'll make two different cannon objects, the cannon "base" and the cannon barrel. Then I could just rotate the cannon barrel when the player presses a key. Unfortunately rotation seems to be hard in webprogramming.
The easiest (now) would be to use the CSS transform property:
const angleInputElement = document.getElementById('angle');
const degrees = angleInputElement.value;
const barrelElement = document.getElementById('barrel'); // I don't see this in your sample though
barrelElement.style.transform = `rotate(${degrees}deg)`;
Also, if I want to animate several objects at the same time, do you think I should just change all the objects in the same gameloop function? Any ideas on this?
For this simple implementation that should work fine.

Categories