Moving Pictures Bugs - JavaScript - 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;

Related

Javascript: code with no animation with requestAnimationFrame?

I am learning Javacript and test the code from the book (below). It should animate an image but doesn't. I add print out using alert which shows that the function is executed only once. What goes wrong?
<!doctype html>
<html>
<head>
<title> My home page </title>
<script>
var cat = document.querySelector("img");
var angle = 0, lastTime = null;
var count = 0;
function animate(time) {
//alert(count);
//++count;
if (lastTime != null)
angle += (time - lastTime) * 0.001;
lastTime = time ;
cat.style.top = (Math.sin(angle) * 20) + "px";
cat.style.left = (Math.cos(angle) * 200) + "px";
requestAnimationFrame(animate);
}
</script>
</head>
<body>
<p style ="text-align: center">
<img src ="img/cat.jpg" style ="position: relative">
</p >
</body>
<script>requestAnimationFrame(animate);</script>
</html>
Thank you for the help.
If you look at the console, you will see that the cat is undefined.
This happens because var cat = document.querySelector("img"); is run in the head element and so the img does not exist yet.
If you move the code at the end of the body it will work.
Or you could run your code when the DOMContentLoaded event is fired.
<!doctype html>
<html>
<head>
<title> My home page </title>
</head>
<body>
<p style ="text-align: center">
<img src ="img/cat.jpg" style ="position: relative">
</p >
</body>
<script>
var cat = document.querySelector("img");
var angle = 0, lastTime = null;
var count = 0;
function animate(time) {
//alert(count);
//++count;
if (lastTime != null)
angle += (time - lastTime) * 0.001;
lastTime = time ;
cat.style.top = (Math.sin(angle) * 20) + "px";
cat.style.left = (Math.cos(angle) * 200) + "px";
requestAnimationFrame(animate);
}
</script>
<script>requestAnimationFrame(animate);</script>
</html>
When the browser see a <script> tag, he stop rendering the page, and run the code inside.
So, the problem in the code that the line var cat = document.querySelector("img"); happen before the img is append to the document, so you query get nothing.
the only change you need to do- is to move the var cat = document.querySelector("img"); to under the body, like so:
</body>
<script>
var cat = document.querySelector("img");
requestAnimationFrame(animate);
</script>
</html>

HTML5/Javascript - Perfect example of Drag and Drop between multiple canvases not working

I have have a problem I am hoping someone will be able to help with...
On my application I require the facility to be able to drag and drop images between multiple canvases.
There are a few pre-made examples of dragging and dropping between multiple canvases avaliable online, and I have found the perfect example for my needs courtesy of 'Richard Heyes' of RGraph which you can see here (NOTE: you must click the image before you can start dragging it).
As you can see, on his website this drag and drop feature works perfectly, however when I transfer the javascript, html and css to my application the ability to drag and drop the image does not work.
What I am doing:
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<style type="text/css">
canvas {
border: 1px solid #808080;
}
</style>
<canvas style="float: left" height="125" width="400" id="cvs1">[No canvas support]</canvas>
<canvas style="float: left; margin-left: 100px" height="125" width="400" id="cvs2">[No canvas support]</canvas>
<script>
window.onload = function ()
{
var canvas1 = document.getElementById("cvs1");
var canvas2 = document.getElementById("cvs2");
var context1 = canvas1.getContext('2d');
var context2 = canvas2.getContext('2d');
var imageXY = {x: 5, y: 5};
/**
* This draws the image to the canvas
*/
function Draw ()
{
//Clear both canvas first
canvas1.width = canvas1.width
canvas2.width = canvas2.width
//Draw a red rectangle around the image
if (state && state.dragging) {
state.canvas.getContext('2d').strokeStyle = 'red';
state.canvas.getContext('2d').strokeRect(imageXY.x - 2.5,
imageXY.y - 2.5,
state.image.width + 5,
state.image.height + 5);
}
// Now draw the image
state.canvas.getContext('2d').drawImage(state.image, imageXY.x, imageXY.y);
}
canvas2.onclick =
canvas1.onclick = function (e)
{
if (state && state.dragging) {
state.dragging = false;
Draw();
return;
}
var mouseXY = RGraph.getMouseXY(e);
state.canvas = e.target;
if ( mouseXY[0] > imageXY.x
&& mouseXY[0] < (imageXY.x + state.image.width)
&& mouseXY[1] > imageXY.y
&& mouseXY[1] < (imageXY.y + state.image.height)) {
state.dragging = true;
state.originalMouseX = mouseXY[0];
state.originalMouseY = mouseXY[1];
state.offsetX = mouseXY[0] - imageXY.x;
state.offsetY = mouseXY[1] - imageXY.y;
}
}
canvas1.onmousemove =
canvas2.onmousemove = function (e)
{
if (state.dragging) {
state.canvas = e.target;
var mouseXY = RGraph.getMouseXY(e);
// Work how far the mouse has moved since the mousedon event was triggered
var diffX = mouseXY[0] - state.originalMouseX;
var diffY = mouseXY[1] - state.originalMouseY;
imageXY.x = state.originalMouseX + diffX - state.offsetX;
imageXY.y = state.originalMouseY + diffY - state.offsetY;
Draw();
e.stopPropagation();
}
}
/**
* Load the image on canvas1 initially and set the state up with some defaults
*/
state = {}
state.dragging = false;
state.canvas = document.getElementById("cvs1");
state.image = new Image();
state.image.src = 'http://www.rgraph.net/images/logo.png';
state.offsetX = 0;
state.offsetY = 0;
state.image.onload = function ()
{
Draw();
}
}
</script>
</body>
</html>
<!-- CODE COURTESY OF RICHARD HEYES OF RGRAPH
http://www.rgraph.net/blog/2013/january/an-example-of-html5-canvas-drag-n-drop.html -->
I have created the same thing on this JSFiddle but the dragging and dropping still does not work.
I am new to html5 and javascript so I am sure it must be something very simple I am overlooking, but I cannot work out what it is.
Your help with this would be much appreciated, thank you very much.
I have inserted your JavaScript code between tags <script> and </script> and move it from JavaScript to HTML and I have added new script link from the example page:
<script src="http://www.rgraph.net/libraries/RGraph.common.core.js" ></script>
JSFiddle - working example
So I think, that you must download and insert core files of RGraph to your code from this page.

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

Error: Unable to set value of the property 'src': object is null or undefined and CSS Error: Error in parsing value for 'top', Declaration dropped

This is the JavaScript portion of my assignment website - it should display a dating ad and on interval move it around the screen, and at each interval it loads a new image
It will randomly move horizontally, but won't move vertically. This problem happens in Firefox - in IE it has no problem.
However in IE it won't iterate over the images, but it does in Firefox.
Could anyone tell me what's going on?
<script type="text/javascript">
var rotatingAd = new Array(3);
var curPosition = 1;
var screenWidth = 0;
var screenHeight = 0;
for(var i = 0; i < 4; ++i)
{
rotatingAd[i] = new Image();
rotatingAd[i].src = "AdDate" + i + ".gif";
}
function openOrderForm()
{
window.open("order.html");
}
function moveAd(){
var leftPos = getRandomLeft();
var topPos = getRandomTop();
document.getElementById("AdDate").style.top = topPos; + "px";//this is where firefox says the css error is
document.getElementById("AdDate").style.left = leftPos + "px";
if(curPosition == 3)
{
curPosition = 0;
}
document.AdDatePic.src = rotatingAd[curPosition].src;//this is where IE gets its null error from
curPosition++;
}
function start(){
screenWidth = document.body.clientWidth;
screenHeight= document.body.clientHeight;
//alert("width="+screenWidth + "height="+screenHeight)
//setTimeout("moveAd()", 3000);
setInterval("moveAd()", 2000);
}
function getRandomLeft(){
var lpos;
lpos = Math.floor(Math.random()*(screenWidth -400));
return lpos;
}
function getRandomTop(){
tpos = Math.floor(Math.random()*(screenHeight - 135));
return tpos;
}
</script>
<body onload="start();">
<span id="AdDate" style="position:absolute; left:300px; top:300px;" >
<img id="AdDatePic" src="AdDate0.gif" alt="picture of gopher" />
</span>
</body>
It looks like your issue with IE is related to how your trying to select the picture tag
changing your code to
document.getElementById("AdDatePic").src
from
document.AdDatePic.src
should fix the IE issue
The firefox issue is from semicolon placement
topPos + "px;"
should fix the issue

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