简体   繁体   中英

Scrolling camera in HTML5 canvas game (with javascript)

I have a simple functioning 2d HTML canvas game, at the moment you can see the whole map, I want there to be a scrolling camera for the canvas game so you can't see the entire map at once, I have no idea how to do this. I've Googled a bit, found nothing.

ctx.drawImage(character,x,y);

canvas already correctly setUp

<canvas id="canvas"></canvas>

There's no errors or bugs

2 way :

1) adjust the positon of the object to draw with the camera offset:

deltaX=object.x-cameraX
deltaY=object.y-cameraY
if(deltaX + object.width > 0
  && deltaX - object.width < cameraWidth 
  &&deltaY + object.height > 0
  && deltaY - object.height < cameraHeight){

    ctx.drawImage(character,deltaX,deltaY);
}

2) have two context and print one into the other

ctxCamera.drawImage(ctx,cameraX,cameraY);

I don't know if I'm too late, but you can encompass the canvas tags with div tags.

HTML:

<div id = "viewport">
  <canvas id="canvas"></canvas>
</div>

CSS:

#viewport{
  overflow: hidden; //so you can't see outside of the div
  width: /*insert desired amount*/px;
  height: /*insert desired amount*/px;
}

Javascript:

function scrollCamera(camx, camy){
  var viewport = document.getElementById('viewport');
  viewport.scrollTop = camy;
  viewport.scrollLeft = camx;
}

scrollCamera(x-/*desired amount*/, y-/*desired amount*/); //makes the camera follow the player

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