1

I have written a javascript that is supposed to scroll pictures across the screen using canvas. I am unable to get this to work and would appreciate any help. I was able to get this to work using one picture and no Array but I want to be able to use an Array and load pictures one after another with a small space between them.

Here's a JSFiddle with my code.

var img = new Image[];

img[0] = new Image;
img[0].src = 'Images/Juniors.jpg';

img[1] = new Image;
img[1].src = 'Images/minis.jpg';

img[2] = new Image;
img[2].src = 'Images/senior.jpg';


var CanvasXSize = 1040;
var CanvasYSize = 240;
var speed = 40; //lower is faster
var scale = 1.05;
var y = -4.5; //vertical offset


var dx = 0.75;
var imgW;
var imgH;
var x = 0;
var clearX;
var clearY;
var ctx;

img.onload = function() {
  imgW = img.width*scale;
  imgH = img.height*scale;
  if (imgW > CanvasXSize) { x = CanvasXSize-imgW; } // image larger than canvas
  if (imgW > CanvasXSize) { clearX = imgW; } // image larger than canvas
  else { clearX = CanvasXSize; }
  if (imgH > CanvasYSize) { clearY = imgH; } // image larger than canvas
  else { clearY = CanvasYSize; }

  ctx = document.getElementById('canvas').getContext('2d');  //Get Canvas Element    
}

function draw() {
//Clear Canvas
ctx.clearRect(0,0,clearX,clearY);

//If image is <= Canvas Size
if (imgW <= CanvasXSize) {
    //reset, start from beginning
    if (x > (CanvasXSize)) { x = 0; }
    //draw aditional image
    if (x > (CanvasXSize-imgW)) {
      ctx.drawImage(img, x-CanvasXSize+1, y, imgW, imgH);
    }
}
//If image is > Canvas Size
else {
  //reset, start from beginning
  if (x > (CanvasXSize)) { x = CanvasXSize-imgW; }
  //draw aditional image
  if (x > (CanvasXSize-imgW)) { ctx.drawImage(img[0],x-imgW+1,y,imgW,imgH); }
}

for(i = 0; i < img.length; i++) {
  ctx.drawImage(img[i],x,y,imgW,imgH);
  //amount to move
  x += dx;
  }
}

doppelgreener
  • 4,809
  • 10
  • 46
  • 63
  • 1
    In what way does it not work? Please create a [JSFiddle](http://jsfiddle.net/) with your JavaScript, and relevant HTML and CSS, so that we can see what's going on and experiment. – doppelgreener May 05 '13 at 22:56
  • Here is the link to a JSFiddle http://jsfiddle.net/dmbarry/CJXzL/ – Dustin Barry May 05 '13 at 23:38
  • Note: `var img = new Array[];` should be `var img = new Array();` (note the brackets) or just `var img = [];` (the two are [identical in this case](http://stackoverflow.com/q/931872/254830)). This was causing a syntax error. – doppelgreener May 06 '13 at 00:03
  • I changed to var img = []; but the program still does not produce the desired result. I do not get any images on the screen. – Dustin Barry May 06 '13 at 00:07
  • This is the first javascript that i have ever written so I'm just learning. – Dustin Barry May 06 '13 at 00:11

1 Answers1

1

To have multiple images loaded when you need them, you shoud use image preloader code:

var imgs=[];
var imagesOK=0;
var imageURLs=[];
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house1.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house2.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house3.jpg");

loadAllImages();

function loadAllImages(){
    for (var i = 0; i < imageURLs.length; i++) {

      // put each image in the imgs array
      var img = new Image();         
      imgs.push(img);

      // after each image has been loaded, execute this function
      img.onload = function(){ 

          // add 1 to imagesOK
          imagesOK++; 

          // if imagesOK equals the # of images in imgs
          // we have successfully preloaded all images
          // into imgs[]
          if (imagesOK>=imageURLs.length ) {

              // all loaded--start drawing the images
              drawImages(); 

          } 
      };    // end onload
      img.src = imageURLs[i];
    } // end for     
}

At this point the images are all loaded, so draw the images

You can use context.translate and context.rotate to tilt your images.

What you do is translate (move) to the center of the image you want to rotate. Then do the rotation from that centerpoint. That way the image will rotate around its center. The rotate function takes a radian angle so you can translate degrees to radians like this: 30 degrees = 30 * Math.PI/180 radians

ctx.translate( left+width/2, topp+height/2 )
ctx.rotate( degrees*Math.PI/180 );

Then you draw your image offset by its centerpoint (remember you’re rotating around that centerpoint)

ctx.drawImage(img,0,0,img.width,img.height,-width/2,-height/2,width,height);

It’s a lot to wrap your head around so here’s example code and a Fiddle: http://jsfiddle.net/m1erickson/t49kU/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

  var canvas=document.getElementById("canvas");
  var ctx=canvas.getContext("2d");

  var imgs=[];
  var imagesOK=0;
  var imageURLs=[];
  imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house1.jpg");
  imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house2.jpg");
  imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house3.jpg");

  loadAllImages();

  function loadAllImages(){
      for (var i = 0; i < imageURLs.length; i++) {
        var img = new Image();
        imgs.push(img);
        img.onload = function(){ 
            imagesOK++; 
            if (imagesOK>=imageURLs.length ) {
                drawImages(); 
            } 
        };    // end onload
        img.src = imageURLs[i];
      } // end for     
  }

  ctx.lineWidth=2;
  var left=25;
  var topp=30;
  var width=100;
  var height=100;
  var rotations=[ -10, 0, 10 ];
  function drawImages(){
      for(var i=0;i<imgs.length;i++){
          var img=imgs[i];
          ctx.save()
          ctx.beginPath();
          ctx.translate( left+width/2, topp+height/2 )
          ctx.rotate(rotations[i]*Math.PI/180);
          ctx.drawImage(img,0,0,img.width,img.height,-width/2,-height/2,width,height);
          ctx.rect(-width/2,-height/2,width,height);
          ctx.stroke();
          ctx.restore();
          left+=125;
      }
  }


}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=400 height=200></canvas>
</body>
</html>
markE
  • 102,905
  • 11
  • 164
  • 176