[英]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.我有一个简单的 2d HTML 画布游戏,目前你可以看到整个地图,我希望画布游戏有一个滚动相机,所以你不能一次看到整个地图,我不知道如何做这个。 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 : 2种方法 :
1) adjust the positon of the object to draw with the camera offset: 1)用相机偏移调整要绘制的对象的位置:
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 2)有两个上下文并将一个打印到另一个
ctxCamera.drawImage(ctx,cameraX,cameraY); ctxCamera.drawImage(ctx,cameraX,cameraY);
I don't know if I'm too late, but you can encompass the canvas tags with div tags.我不知道我是否为时已晚,但您可以使用 div 标签包含画布标签。
HTML: HTML:
<div id = "viewport">
<canvas id="canvas"></canvas>
</div>
CSS: CSS:
#viewport{
overflow: hidden; //so you can't see outside of the div
width: /*insert desired amount*/px;
height: /*insert desired amount*/px;
}
Javascript: 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.