简体   繁体   中英

Scrolling Pictures with javascript

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM