1
\$\begingroup\$

If inside a canvas I draw a box, and the I add arrows to move it, the box will eventually be out of my reach since it goes out the border and I cant see it. How could I follow the box so that it is always in the center?

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

Is simple, you have to use a simple "camara" system and make the cube or item or player be the center of it, so...done

Here's an example of a camera in pure javascript

Use arrows to move the camera

var map = [];

for(var t = 0; t < 100; t++){
  var r = [];
  for(var tt = 0; tt < 100; tt++)
    r.push(Math.floor(Math.random()*4));
  map.push(r);
}

var color = ["blue","red","orange","green"];

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

var camera = {x:0,y:0};
var fov = 5;
var ts = canvas.height/fov;

Draw();

document.addEventListener("keydown", move);

function move(e){
  e.preventDefault();
  
  switch(e.keyCode){
    case 38:
      if(camera.y-1 >= 0 && camera.y-1 <= 100)
      camera.y--;
    break;
    case 39:
      if(camera.x+1 >= 0 && camera.x+1 <= 100)
      camera.x++;
    break;
    case 40:
      if(camera.y+1 >= 0 && camera.y+1 <= 100)
      camera.y++;
    break;
    case 37:
      if(camera.x-1 >= 0 && camera.x-1 <= 100)
      camera.x--;
    break;
  }
  Draw();
}

function Draw(){
  for(var x = 0; x < fov; x++){
    for(var y = 0; y < fov; y++){
        var rpos = {
          x: Math.round(camera.x - fov/2) +x,
          y: Math.round(camera.y - fov/2) +y
        };
    
        ctx.save();
      
        try {
          var tile = map[rpos.x][rpos.y];
          ctx.fillStyle = color[tile];
          ctx.fillRect(x*ts, y*ts, ts, ts);
        } catch(e) {
          ctx.fillStyle = "black";
          ctx.fillRect(x*ts, y*ts, ts, ts);
        }
        ctx.restore();
    }
  }
}
canvas {
    border: 1px solid grey;
  }
<body>
<canvas id="canvas"></canvas>
  </body>

\$\endgroup\$
2
  • \$\begingroup\$ Im not understanding, that color blocks you have, what are they? Are you moving the boxes with the keyboard? \$\endgroup\$ Jan 24, 2016 at 1:44
  • \$\begingroup\$ Color boxes are random generated tiles who makes a map, each o them has a random color just to be able of track the map position...with arrows you move the camera, so you can control which chunck of map you can see and wich not \$\endgroup\$
    – PRDeving
    Jan 24, 2016 at 10:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .