Home > other >  Infinite image movement using canvas
Infinite image movement using canvas

Time:09-21

class Obstacle {
  constructor(image, x, y, w, h) {
    this.image = image;
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;

    this.dx = gameSpeed;
  }

  animate() {
    this.x  = this.dx;
    this.draw();
    this.dx = gameSpeed; 
  }

  draw() {

//////1
    var pat = ctx.createPattern(landImage, "repeat-x");
    ctx.fillStyle = pat;
    ctx.fillRect(this.x, this.y, this.w, this.h);
//////2
    ctx.drawImage(pat, this.x, this.y, this.w, this.h);
  }
}

function update() {
  requestAnimationFrame(update);
  ctx.clearRect(0, 0, canvas.width, canvas.height);  

    ... etc code...

  terrain.animate();
}

function start() {

    ...etc code...

  terrain = new Obstacle(landImage, 0, canvas.height - 20, 20000, 20);
  update();
}
start();

Terrain image

terrain

Question

I'm trying to make a t-rex game. I want to make the ground constantly move when Dino (runner) moves.

It is not the ctx.translate() function that moves the image in my code, but The 'this.dx' coordinate value of the Class is moved using the requestAnimationframe() function.

The First Code written as '/////2' does not move the ground indefinitely.
A solution code written as '/////1', but it did not work.

How can I implement land that moves indefinitely?

CodePudding user response:

I found the answer myself. I hope this question helps those who read it.

enter image description here

Reference : https://jongbeom-dev.tistory.com/109

It was a problem to store as much as the part where the background image disappears in the offset variable and draw as much as the corresponding coordinate value. //left //right divided into two parts and drew a background image.

  animate() {
    this.x  = this.dx;
    this.draw();
    this.dx = gameSpeed;
    //그림의 최대길이는 2380 * 23 (px)
    if (offset > 2300) offset = 0;
    else offset  = this.dx;
  }

  draw() {
    // left
    ctx.drawImage(
      this.image,
      2380 - offset,
      0,
      offset,
      23,
      0,
      canvas.height - this.h,
      offset,
      this.h
    );
    // right
    ctx.drawImage(
      this.image,
      0,
      0,
      2380 - offset,
      23,
      offset,
      canvas.height - this.h,
      2380 - offset,
      this.h
    );
  }
  • Related