Simple javascript html image game - javascript

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

Related

HTML CANVAS - Preload Issue or OnLoad issue - Why do I have to click twice?

I have an HTML page with 2 canvases side-by-side. The left one has a clickable upper region. The right one is where all the drawing takes place. I want the user to click the region on the left, which will load a new image on the right, and replace the one that is already there, but I have to click twice for the new image to show up. Why is this? See code.
THE HTML
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
#centerAll {
margin-left:auto;
margin-right:auto;
width:1300px;
}
</style>
</head>
<body>
<div id="centerAll">
<canvas id="TheLeftCanvas" width="300" height="500"
style="border:2px solid #999999;"></canvas>
<canvas id="TheRightCanvas" width="900" height="500"
style="border:2px solid #999999;"></canvas>
<script type="text/javascript" src="whyClickTwiceForImage.js">
</script>
</div>
</body>
</html>
AND THE JAVASCRIPT
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded () {
canvasApp();
}
function canvasApp() {
var rightCanvas = document.getElementById("TheRightCanvas");
//THE EMPTY CANVAS ON THE RIGHT, WHICH DRAWS THINGS
var rightCtx = rightCanvas.getContext("2d");
var leftCanvas = document.getElementById("TheLeftCanvas");
//THE EMPTY CANVAS ON THE LEFT, WHICH HANDLES USER CLICKS
var leftCtx = leftCanvas.getContext("2d");
var currentMouseXcoor = 0;
var currentMouseYcoor = 0;
var imagesToLoad = 0; //USED TO PRE-LOAD SOME OTHER VISUALS, BEFORE THE USER STARTS
var imagesLoaded = 0;
var picturesTheUserCanChoose = ["pic01.png", "pic02.png",
"pic03.png", "pic04.png", "pic05.png"];
var nameOfPicTheUserChose = "pic05.png"; //LET'S JUST SAY "pic05.png" IS A PLACEHOLDER PICTURE... TO START OFF
var legitMouseClick = 0; //DID THE USER CLICK IN THE UPPER REGION OF THE LEFT CANVAS?
var loaded = function(){ // "LOADED" AND "LOAD IMAGE" ARE USED TO PRELOAD ALL THOSE OTHER VISUALS BEFORE THE USER STARTS
imagesLoaded += 1;
if(imagesLoaded === imagesToLoad){
imagesToLoad = 0;
imagesLoaded = 0;
drawScreen(); // OK... ALL LOADED.... SO DRAW THE SCREEN
}
}
var loadImage = function(url){ // "LOADED" AND "LOAD IMAGE" ARE USED TO PRELOAD ALL THOSE OTHER PICS BEFORE THE USER STARTS
var image = new Image();
image.addEventListener("load",loaded);
imagesToLoad += 1; // ADD THE NUMBER TO THE IMAGES NEEDED TO BE LOADED
image.src = url;
return image; // ...AND RETURN THE IMAGE
}
//--------------------------------------------------------------
leftCanvas.addEventListener('mouseup', function(evt) { var
mousePos = doMouseUp(leftCanvas, evt);
currentMouseXcoor = mousePos.x; currentMouseYcoor =
mousePos.y; processMousePosition();}, false);
//--------------------------------------------------------------
function drawScreen(){
clearScreen();
rightCtx.drawImage(picture1,0,0,100,100);
}
//THIS FUNCTION PRESUMABLY LOADS IMAGES ON-THE-FLY... BUT WHY DOES THE LEFT CANVAS REGION HAVE TO BE CLICKED TWICE FOR THE NEW IMAGE TO SHOW?
function processMousePosition() {
if(currentMouseYcoor >= 0 && currentMouseYcoor <= 50){
//IF THE CLICK IS IN THE UPPER REGION OF THE LEFT CANVAS
nameOfPicTheUserChose = picturesTheUserCanChoose[0];
//WE'LL SAY THE USER CHOSE THE VERY FIRST PIC IN THE ARRAY
picture1.src = ("picturesFolder/"+ nameOfPicTheUserChose);
picture1.onload = legitMouseClick = 1;//I JUST MADE UP FOR SOMETHING TO HAPPEN WHEN THE NEW PICTURE LOADS???
alert(nameOfPicTheUserChose); // THE ALERT CORRECTLY SHOWS THE NAME OF THE FIRST PIC IN THE ARRAY
}
drawScreen();
}
function doMouseUp(leftCanvas, evt){
var rect = leftCanvas.getBoundingClientRect();
return { x: evt.clientX - rect.left, y: evt.clientY - rect.top};
}
function clearScreen(){
rightCtx.clearRect(0, 0, 900, 500);
leftCtx.clearRect(0, 0, 300, 500);
}
//var someOtherVisual1 =
//loadImage("backgroundArtFolder/someOtherVisual1.jpg");
//var someOtherVisual2 =
//loadImage("backgroundArtFolder/someOtherVisual2.png");
//var someOtherVisual3 =
//loadImage("backgroundArtFolder/someOtherVisual3.png");
//var someOtherVisual4 =
//loadImage("backgroundArtFolder/someOtherVisual4.png");
//var someOtherVisual5 =
//loadImage("backgroundArtFolder/someOtherVisual5.png");
var picture1 = loadImage("picturesFolder/pic05.png");
//LET'S JUST PRELOAD "pic05.png" AS A PLACEHOLDER... TO START OFF
}
You can change the image load on click in js file picture1.src = ("picturesFolder/"+ nameOfPicTheUserChose); to picture1 = loadImage("picturesFolder/"+nameOfPicTheUserChose); and picture1.onload = legitMouseClick = 1; to 'legitMouseClick = 1'

Moving Pictures Bugs - JavaScript

After abt 2hrs or so, I managed to get the images moving, but i met with some issues:
1) Images move beyond the "bound" - image overlap is ok, but beyond the side of the browser
2) Moving the scroll bar to the right (0 -> 20) makes the image move closer - OK
but moving the scroll bar to the left (20 -> 0) does not return the images back to where they were
I seek you guys assistance to help debug and clean the code.
Thank You in advance :) and apologies for my weak sense of coding >.<
Images Used:
lion tail
lion head
Below is the "Draft" HTML Code:
<!DOCTYPE html>
<html>
<head>
<title>Moving Image</title>
<script src="./movingPicture.js" type="text/javascript"></script>
</head>
<body>
<form>
<img id="IMG_LEFT" src="./lion tail.gif" />
<img id="IMG_RIGHT" src="./lion head.gif" />
<p>Move the Bar to Move the Images Closer</p>
<input type="range" min="0" max="100" value="0" steps="2" oninput="moveRight(value);"/>
</form>
</body>
</html>
Below is the Javascript Code:
var imgObjLeft = null;
var imgObjRight = null;
function init()
{
imgObjLeft = document.getElementById('IMG_LEFT');
imgObjLeft.style.position= 'relative';
imgObjLeft.style.left = '0px';
imgObjRight = document.getElementById('IMG_RIGHT');
imgObjRight.style.position= 'relative';
imgObjRight.style.left = '100px';
}
function moveRight(value)
{
valueH = value/2;
imgObjLeft.style.left = parseInt(imgObjLeft.style.left) + valueH + 'px';
imgObjRight.style.left = parseInt(imgObjRight.style.left) - valueH + 'px';
}
window.onload =init;
Try the following JS. You dont seem to give a range for the movement of these images. I have added a limit which is the max value of your range control. you can increase the value by increasing the max value of your slider
var imgObjLeft = null;
var imgObjRight = null;
function init() {
imgObjLeft = document.getElementById('IMG_LEFT');
imgObjLeft.style.position = 'relative';
imgObjLeft.style.left = '0px';
imgObjRight = document.getElementById('IMG_RIGHT');
imgObjRight.style.position = 'relative';
imgObjRight.style.left = '100px';
}
function moveRight(value) {
valueH = value;
imgObjLeft.style.left = valueH + 'px';
imgObjRight.style.left = (100 - valueH) + 'px';
}
window.onload = init;

javascript - create image element and randomly place within div in html5

In my html document I have a div with id="containerRight". In the same directory where the html document is I have an image that needs to be added to the html. Using javascript I want to add 5x the same image into the div and scatter them randomly within the div. I'm struggling with adding 5x the same image from the hdd and positioning them randomly within the div. I have tried this so far:
<!DOCTYPE html>
<html>
<head>
<script>
function insert_picture(){
var newPicture = document.createElement("img");
var destinationParent = document.getElementByID("containerRight");
destinationParent.appendChild(newPicture);
}
function ImgRandomPosition()
{
var left = generateRandom();
var top = generateRandom();
var image = insert_picture();
var imagestyle = document.getElementById("imgRight").style;
imagestyle.position = "absolute";
imagestyle.top = top;
imagestyle.left = left;
}
</script>
</head>
<body onclick="insert_picture()">
<div id="containerRight">
<img id="imgRight" src="smiley.png" alt="" />
</div>
</body>
</html>
I have changed the code to the following and it adds images to the div containerRight next to each other:
function insert()
{
var imgDestination = document.getElementById("containerRight");
var imgAdded = document.createElement("img");
imgAdded.src = "smiley.png";
imgDestination.appendChild(imgAdded);
}
Then the next issue is to position images randomly within the same div id="containerRight".
The code below does add images randomly to the body of the html not the div.
Any further thoughts greatly appreciated:
function insert()
{
var imgDestination = document.getElementById("containerRight");
var imgAdded = document.createElement("img");
imgAdded.src = "smiley.png";
imgDestination.appendChild(imgAdded);
ImgRandomPosition(imgAdded);
}
function ImgRandomPosition(imgAdded)
{
var left = Math.floor((Math.random() * 400) + 1)+"px";
var top = Math.floor((Math.random() * 400) + 1)+"px";
var imagestyle = imgAdded.style;
imagestyle.position = "absolute";
imagestyle.top = top;
imagestyle.left = left;
}
change your code to
function insert_picture()
{
var newPicture = document.createElement("img");
var destinationParent = document.getElementByID("containerRight");
destinationParent.appendChild(newPicture);
newPicture.src = "smiley.png";
ImgRandomPosition(newPicture);
}
function ImgRandomPosition(imgObj)
{
var left = generateRandom();
var top = generateRandom();
var imagestyle = imgObj.style;
imagestyle.position = "absolute";
imagestyle.top = top;
imagestyle.left = left;
}
Now when you click on the body <body onclick="insert_picture()"> this method will add an image somewhere on the body

Get the images dimension from html

I have two images in two different section and div.I want to get the original dimension at same time and send to my java script file to do some calculation. How do I get the images dimension at the same time.
html file
<section id ="hi">
<img src = "images/hi.png" onload = "OnImageLoad(event);" />
</section>
<section id = "bye">
<img src = "images/hi.png" onload = "OnImageLoad(event);"/>
</section>
js
function OnImageLoad(evt) {
var img = evt.currentTarget;
// what's the size of this image
var w = $(img).width();
var h = $(img).height();
In this code I am able to get the images dimension of images,But they return dimension of only one images.I want to get the dimension of both images at same time.
Something like this:
function OnImageLoad(evt) {
var img1 = evt.currentTarget;
var img2 = evt.currentTarget;
// what's the size of this image
var w1 = $(img1).width();
var h1 = $(img1).height();
var w2 = $(img2).width();
var h2 = $(img2).height();
You can not do that, they are async tasks. You can only calculate the size of the image only when they are completely loaded, so If first image is of higher size then the second image, it will take more time to calculate the first image size then the second.
What you can do is, fetch both the image sizes aynchronously, and when both of them are done you can do the calculations.
var sizes = [];
var counter = 0;
function OnImageLoad(evt) {
var img = evt.currentTarget;
// what's the size of this image
var w = $(img).width();
var h = $(img).height();
counter++;
sizes.push({
height: h,
width: w
});
if (counter == 2) {
callAnotherFunction(sizes)
}
}
prepending the variables with a custom value should make it possible.
HTML
<section id ="hi">
<img src = "images/hi.png" onload = "OnImageLoad(event,1);" />
</section>
<section id = "bye">
<img src = "images/hi.png" onload = "OnImageLoad(event,2);"/>
</section>
JS
function OnImageLoad(evt, pre) {
var img = evt.currentTarget;
// what's the size of this image
eval("var w" + pre + " = $(img).width()");
eval("var h" + pre + " = $(img).height()");
Ive not tested this though.
function OnImageLoad() {
var img1 = document.getElementById("Image1");
var img2 = document.getElementById("Image2");
// what's the size of this image
var w1 = img1.width;
var h1 = img1.height;
var w2 = img2.width;
var h2 = img2.height;
}
Html:
<section id ="hi">
<img id="Image1" src = "images/hi.png"/>
</section>
<section id = "bye">
<img id="Image2" src = "images/hi.png"/>
</section>
Call this function on window.onload=OnImageLoad();
function OnImageLoad(evt) {
//This function will be called on each image load and will iterate all the image inside this dom
var images = $('img');
for(var i =0 ;i<images.length; i++) {
// what's the size of this image
var w = $(images[i]).width();
var h = $(images[i]).height();
//For each file you will have width and height of the image
console.log('width of image-'+i+': ',w);
console.log('height of image-'+i+': ',h);
}
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.7.2.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<section id ="hi">
<img src = "http://cdn.mysitemyway.com/etc-mysitemyway/icons/legacy-previews/icons-256/3d-glossy-green-orbs-icons-business/103491-3d-glossy-green-orb-icon-business-tool-screwdriver.png" onload = "OnImageLoad(event);" />
</section>
<section id = "bye">
<img src = "http://cdn.mysitemyway.com/etc-mysitemyway/icons/legacy-previews/icons-256/3d-glossy-orange-orbs-icons-business/105429-3d-glossy-orange-orb-icon-business-tool-hammer4-sc44.png" onload = "OnImageLoad(event);"/>
</section>
</body>
</html>
enter link description here

javascript image position

I'm trying to put smile images at random positions on the left side div.But the images are not appearing in random order , rather it is showing images serially. Why is this happening?
<html>
<head>
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left</p>
<div id= "leftSide"></div>
<div id = "rightSide"></div>
<style>
img1 {position:absolute}
div {position:absolute; width:500px;height: 500px}
#rightSide {left:500px;border-left: 1px solid black}
</style>
<script>
var numberOfFaces =5,i;
var theLeftSide = document.getElementById("leftSide");
function generateFaces()
{
for( i=0;i<numberOfFaces;i++)
{
var img1 =document.createElement("img");
img1.src = "smile.png";
var topran = Math.random() * 400;
var topran = Math.floor(topran);
var leftran = Math.random() *400;
var leftran = Math.floor(leftran);
img1.style.top = topran + "px";
img1.style.left = leftran + "px";
theLeftSide.appendChild(img1);
}
}
</script>
</head>
<body onload = "generateFaces()">
</body>
</html>
You can't style your smile image with img1 {position:absolute} in your CSS. Change your CSS to .smile {position:absolute} (a class selector) and set the class smile on img1.
var img1 =document.createElement("img");
img1.src = "smile.png";
img1.className = "smile";
img1 is not a valid CSS selector. Change it to just img or #leftSide img

Categories