Help moving a picture with JavaScript

Started by
8 comments, last by Barzai 11 years, 2 months ago

I have a stupid problem at the moment when learning JavaScript. I just want to move this simple image, but it doesn't work at all. Can someone see the problem? I will remove all the not so important code. I need some kind of repaint method or somethin I think. How shall I solve this?


<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
      #myCanvas {
        border: 1px solid #9C9898;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="400"></canvas>
    <script>
     
   var paddle;
   var score;
   var timer;
   var dx = 0;
   var dy = 0;
   var paddleX = 300;
   var paddleY = 50;
   var s1x = -1;
   var s1y = 0;
   var star1X = 0;
   var star1Y = 0;
var requestAnimFrame =  window.requestAnimationFrame ||
                        window.webkitRequestAnimationFrame ||
                        window.mozRequestAnimationFrame ||
                        window.oRequestAnimationFrame ||
                        window.msRequestAnimationFrame ||
                        function(callback) {
                            window.setTimeout(callback, 1000 / 60);
                        };

 var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      var imageObj = new Image();

   
function init(){
   paddle = document.getElementById('paddle');
   document.onkeydown = keyListener; 
   document.onkeyup = keyListener;
   timer = setTimeout('init()',50);
   move();
   keyMoving();
}

function keyListener(e){

}

imageObj.onload = function() {
        context.drawImage(imageObj, paddleX, paddleY);
      };
        imageObj.src = 'ball.PNG';  



function keyMoving(){
  
 document.onkeydown = function(event) {
 event = event || window.event;

 var e = event.keyCode;

// Left
   if(e==37){
      dx = -4;    
   }
  
//Up
 if(e==38){
      dy = -4;  
   }
// Right
   if(e==39){
      dx = 4;
   }
 
// Down
   if(e==40){
     dy = 4;   
   }
}
}

function move(){
paddleX += dx;
paddleY += dy;
}

</script>
  </body>
</html>
Advertisement

I solved the problem myself, no worries!

take a look at a sample of mine, see the page source - it has basic game loop and key binding as well using jquery. maybe it will help you.

That was a nice looking "game" for beeing made in JS! I checked the code.

I have a new problem now and maybe I can use this existing thread for that problem instead of creating a new one. I don't know about how "classes" and arrays work in JavaScript. I want for example to create (in Java) a class called bullet (startX, startY) and then I want to create an arraylist bullets and then I would like to paint the bullets somehow and then bullets.add(x,y); in the end to create my bullet object.

I don't know how to do this in JavaScript though. Can someone help me with that? Here is my code by now. Just ignore everything except the bullet things that I've been trying to create. Do you have some advice?


<html>
<head>
    <meta http-equiv = "Content-type" content = "text/html;charset=utf-8">
    <meta name = "viewport" id = "viewport" content = "width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;"/>
    <script type = "text/javascript">
       
var paddle;
   var score;
   var timer;
   var dx = 0;
   var dy = 0;
   var paddleX = 20;
   var paddleY = 200;
   var s1x = -1;
   var s1y = 0;
   var stars1X = 0;
   var stars1Y = 0;
    var s2x = -2.5;
   var s2y = 0;
   var stars2X = 0;
   var stars2Y = 0;
    var s3x = -4.5;
   var s3y = 0;
   var stars3X = 0;
   var stars3Y = 0;
   var moveDirection = false;
var snd = new Audio("rymd2.wav");
snd.loop = true;
snd.play();
//var bullets [];
    
        function drawPic()
        {
            ////////////// DOESN'T WORK /////////////////// 
            var canvas = document.getElementById('mainCanvas');
            if (canvas.getContext)
            {
                var context = canvas.getContext('2d');
                var img = new Image();
                var background = new Image();
                var stars1 = new Image();
                var stars2 = new Image();
                var stars3 = new Image();
                var lol = new Image();
                img.onload = function ()
                {
                    context.drawImage(background,0,0);
                    
                // Stars1
                context.drawImage(stars1,stars1X,stars1Y);
                context.drawImage(stars1,stars1X+800,stars1Y);      
                if(stars1X + 800 < 0){
                    context.drawImage(stars1,stars1X,stars1Y);
                    stars1X = 0;
                }
                // Stars2
                 context.drawImage(stars2,stars2X,stars2Y);
                context.drawImage(stars2,stars2X+800,stars2Y);      
                if(stars2X + 800 < 0){
                    context.drawImage(stars2,stars2X,stars2Y);
                    stars2X = 0;
                }
                // Stars3
                 context.drawImage(stars3,stars3X,stars3Y);
                context.drawImage(stars3,stars3X+800,stars3Y);      
                if(stars3X + 800 < 0){
                    context.drawImage(stars3,stars3X,stars3Y);
                    stars3X = 0;
                }
                               
                    context.drawImage(img, paddleX, paddleY);

                };
                if(moveDirection == true){
                img.src = "planeRight.gif";
            }
                if(moveDirection == false){
                img.src = "planeLeft.gif"; 
            }
                background.src = "background.png";
                stars1.src = "background3a.png";
                stars2.src = "background3b.png";
                stars3.src = "background3c.png";
                lol.src = "boss.gif";
               
            }


        }

function init(){

   paddle = document.getElementById('paddle');
   document.onkeydown = keyListener; 
 document.onkeyup = keyListener;
   timer = setTimeout('init()',30);
   move();
   keyMoving();
   drawPic();
//for(int i = 0; i < 10; i++){
  //bullets [i] = new bullet(30,33);
//}

}

function keyListener(e){

}

function keyMoving(){
  
 document.onkeydown = function(event) {
 event = event || window.event;

 var e = event.keyCode;

 if(!e){
      
      e = window.event;
   }

// Left
   if(e==37){
      moveDirection = false;
      dx = -4;  
        
   }
  
//Up
 if(e==38){
    // bullets[0] = new bullet(30,30);
      dy = -4;  
   }
// Right
   if(e==39){
       moveDirection = true;
      dx = 4;
   }
 
// Down
   if(e==40){
     dy = 4;   
   }
}
/////////////////////////

 document.onkeyup = function(event) {
 event = event || window.event;

 var e = event.keyCode;

 if(!e){
      
      e = window.event;
   }

// Left
   if(e==37){
      dx = 0; 

   }
  
//Up
 if(e==38){
      dy = 0;   
   }
// Right
   if(e==39){
      dx = 0;
   }
 
// Down
   if(e==40){
     dy = 0;   
   }
}

}

function move(){
paddleX += dx;
paddleY += dy;
stars1X += s1x;
stars2X += s2x;
stars3X += s3x;

}

function bullet(startX, startY){
  var x = startX;
  var y = startY;
context.drawImage(lol, x, y);

}

    </script>
</head>
<body onload = "init();">
    <canvas id = "mainCanvas" width="800" height="600"></canvas>
</body>
</html>

When you make your object prototype, use the this keyword to store your passed in parameter as part of your object. So, your bullet prototype would look more like this:

function bullet(startX, startY){

this.x = startX;

this.y = startY;

}

This link gives a general overview of how OOP in Javascript using prototyped objects works:

https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript

I find that MDN is a pretty good resource for javascript, so googling 'mdn javascript [insert whatever you're trying to research here]' gives me good results.

Good luck

Thank you, that was a very good soucre. I will try to use mdn when I search for stuff. Though I just didn't really get the thing with the Images that I want. If I want my "bullet" to be of an image so that you can see something. By looking at my code, how shall I apply It in my bullet class?

It would be nice to have some kind of easy code for how to use images in objects (like a setImage-function) and how to create it (and where to put everything).

There are many approaches, but I personally like this one.


function CreateBullet(startX, startY)
{
   //these will be private
   var x = startX || 0;
   var y = startY || 0;

   var Bullet = function()
   {
   }

   Bullet.prototype.getX = function()
   {
      return x;
   }
   
   Bullet.prototype.getY = function()
   {
      return y;
   }
   
   Bullet.prototype.move = function(dx,dy)
   {
      x += dx;
      y += dy;
      return this;
   }

   return new Bullet();
}

var bullet = CreateBullet(0,0);
bullet.move(1,2);

Thanks, that was kind of what I was looking for. What about the Image/DragImage thing?! How am I supposed to do that? That's my main issue :)

Maybe it is your keyListener function? You attach keyListener to document.onkeydown and document.onkeyup, but keyListener has no code in it.

Also, if you'd like to read up more on the type of code that EmployeeNumber8 posted, that was a closure. Javascript supports closures, and they're quite popular.

As far as making your bullets visible, unfortunately I can't help with that. I haven't used canvas, so any input I give about it would be guessing at best. I've been making my game images by stacking or arranging solid background color divs. I know it's kind of silly, but it's a lot of fun so I'm going with it.

MDN may have more good input about HTML canvas, though. It's worth a shot.

This topic is closed to new replies.

Advertisement