Moving character and map with canvas + js

1
Well I have a question, I would like to know how I could use the image at normal size, but I can navigate it with the directional left and right, eg I have a canvas of size 968 width and 643 height, and I have one image of 643 tall and 2000 width ( link ), how would I move a character (sprite) inside it and moving it on the map ? without it exceeding the limit of the parent image

    
asked by anonymous 18.06.2016 / 04:39

2 answers

2

You need a camera or viewport system. It uses the% w / w of the canvas, which already moves all the objects drawn accordingly and does not have to be calculated relative positions, and then draws everything with coordinates relative to the world (the image):

var iw = 2000; //Image width
var ih = 643; //Image height
var sw = 968; //Canvas width
var sh = 643; //Canvas height
var cw = 50; //Character width
var ch = 50; //Character height
var speed = 10; //Character speed

var img = new Image(iw, ih);
img.src = "http://i.imgur.com/QnBufq4.jpg";
var ctx = canvas.getContext("2d");
var pos = {x: 0, y: ih - 140};
var camera = {x: 0, y: 0}

function draw() {
 //Faz a esquerda da câmera começar meia tela antes do personagem, mas só se tiver imagem suficiente pra isso
 camera.x = Math.min(iw - sw, Math.max(0,pos.x - sw/2));
 //Reseta as transformações do canvas
 ctx.setTransform(1,0,0,1,0,0);
 //Limpa o canvas
 ctx.clearRect(0, 0, canvas.width, canvas.height);
 //Desloca o mundo inteiro, simulando uma câmera
 ctx.translate(-camera.x, -camera.y);
 //Desenha o fundo
 ctx.drawImage(img, 0, 0, sw, sh, 0, 0, iw, ih);
 //Desenha o personagem
 ctx.fillRect(pos.x, pos.y, cw, ch);

 window.requestAnimationFrame(draw);
}

document.addEventListener('keydown', function(e) {
 var key = e.which || e.key || e.keyCode;
 switch(key) {
  case 37: pos.x-=speed; break;
  case 39: pos.x+=speed; break;
 }
 pos.x = Math.max(0, Math.min(iw - cw,pos.x));
});

window.requestAnimationFrame(draw);
<canvas style="border: 1px solid black;" id="canvas" width="968" height="643">
</canvas>

And here, if you'd like, a more in-depth tutorial: Panning and scrolling background images using the canvas element

    
18.06.2016 / 21:04
-1

Good evening my dear. I'm not giving you a solution in code, but I already tell you that the solution is not to move the character, but the image behind using parallax.

An example of how the parallax works link

If you see a solution to this, I'll help you with the situation.

    
18.06.2016 / 04:54