Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Moving imgs y position up and down;

1. ## Moving imgs y position up and down;

Hey guys;

I've been trying to wrap my head around this for ages and can't seem to figure this out. Anyways, to the question;

Basically I have a Canvas in my HTML 300x300 and would like to get an image
to move down from the top, but when it gets to the bottom, it goes back up, and henceforth.

Here's the coding i've got so far.
Code:
```var ctx;
var img;
var x = 0;
var y = 40;

function setupCanvas() {
var canvas = document.getElementById('Canvas');
if (canvas.getContext) {
ctx = canvas.getContext('2d');
setInterval('draw();', 36);
img = new Image();
img.src = '../images/updownarrow.png';
}
}
function draw() {
drawBackground();
ctx.drawImage(img, x, y);
y += 2;
if(y >= 290 ){
y -= 4;
}
}```
The bold part is the "issue" part;

Everytime the image falls below 290 it attempts to go up,
but because the value drops under 290 it continues to go down.
Then comes a big struggle point for the image constantly going up and down near the 290 y point.

Sorry if this is a basic question; just started learning Javascript n_n;
Thanks.

• Not tested, but I think following logic will work...

Code:
```var lowerBound_Y = 40,
upperBound_Y = 290,
increment_Y = 2,
DOWN = 0,
UP = 1
DIRECTION = DOWN;

function draw() {
drawBackground();
ctx.drawImage(img, x, y);
if(DIRECTION == DOWN) {
y += increment_Y;
if(y >= upperBound_Y) {
DIRECTION = UP;
}
}
else if(DIRECTION == UP) {
y -= increment_Y;
if(y <= lowerBound_Y) {
DIRECTION = DOWN;
}
}
}```
Or the shorter code
Code:
```var lowerBound_Y = 40,
upperBound_Y = 290,
increment_Y = 2,
goingDown = true;

function draw() {
drawBackground();
ctx.drawImage(img, x, y);
y += goingDown ? increment_Y : -increment_Y;
if( (goingDown && y >= upperBound_Y) ||
(!goingDown && y <= lowerBound_Y) )
goingDown = !goingDown;
}```

• ## Users who have thanked niralsoni for this post:

• Awesome, Thanks buddy.
Much appreciated (:

•