简体   繁体   中英

I want to make a viewport for a canvas game

So I have a game(that is more of a map) that loads a bunch of tiles and places them together. The tiles load just fine, but I'd like to move the viewport. I've looked into this subject, and I have a function that checks the keyboard. If 'd' is being pressed, I'd like to move the canvas so the viewport sees something different.

So far, the function for moving the canvas right looks like this:

function moveRight() {
ctx.translate(3000, 0);
imageSearch();
};

Where the imageSearch function updates the canvas. The updating, and loading etc. works fine, I just can't figure out how to move the canvas. Help would be appreciated, thanks in advance.

EDIT:

Here's a JSFiddle that 1j01 fixed for me: jsfiddle.net/jujhp0yv/1

The canvas still doesn't move though, so I'm still awaiting your responses :)

Try storing the view port in a variable.

var view = {x: 0, y: 0};

Then, at the beginning of your draw loop / render function, save the canvas state and translate to the view port.

ctx.save();
ctx.translate(view.x, view.y);

If you want view.x and view.y to represent the center of the view, instead translate like this:

ctx.translate(view.x - canvas.width/2, view.y - canvas.height/2);

At the end of your draw loop / render function, restore the state so translations won't stack up.

ctx.restore();

Now you should be able to modify view.x and view.y to move the view. (eg view.x += 5 )

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