Try to search your question here, if you can't find : Ask Any Question Now ?

HTML5 Canvas camera/viewport – how to actually do it?

HomeCategory: stackoverflowHTML5 Canvas camera/viewport – how to actually do it?
Avatarpushpa asked 3 months ago

I’m sure this was solven 1000 times before: I got a canvas in the size of 960*560 and a room in the size of 5000*3000 of which always only 960*560 should be drawn, depending on where the player is. The player should be always in the middle, but when near to borders – then the best view should be calculated). The player can move entirely free with WASD or the arrow keys. And all objects should move themselves – instead of that i move everything else but the player to create the illusion that the player moves.

I now found those two quesitons:

HTML5 – Creating a viewport for canvas works, but only for this type of game, i can’t reproduce the code for mine.

Changing the view "center" of an html5 canvas seems to be more promising and also perfomant, but i only understand it for drawing all other objects correctly relative to the player and not how to scroll the canvas viewport relative to the player, which i want to achieve first of course.

My code (simplified – the game logic is seperately):

var canvas = document.getElementById("game");
canvas.tabIndex = 0;
var cc = canvas.getContext("2d");

// Define viewports for scrolling inside the canvas

/* Viewport x position */   view_xview = 0;
/* Viewport y position */   view_yview = 0;
/* Viewport width */        view_wview = 960;
/* Viewport height */       view_hview = 560;
/* Sector width */          room_width = 5000;
/* Sector height */         room_height = 3000;

canvas.width = view_wview;
canvas.height = view_hview;

function draw()

    // World's end and viewport
    if (player.x < 20) player.x = 20;
    if (player.y < 20) player.y = 20;
    if (player.x > room_width-20) player.x = room_width-20;
    if (player.y > room_height-20) player.y = room_height-20;

    if (player.x > view_wview/2) ... ?
    if (player.y > view_hview/2) ... ?

The way i am trying to get it working feels totally wrong and i don’t even know how i am trying it… Any ideas? What do you think about the context.transform-thing?

I hope you understand my description and that someone has an idea. Kind regards

1 Answers
Best Answer
Avatarnaveen answered 3 months ago
Your Answer

3 + 16 =

Popular Tags

WP Facebook Auto Publish Powered By :