Code is here ( https://gist.github.com/a17216d5b1db068ab41b )
Taking a break from a client project today and decided to try something real quick out. For one of my unpublished pet projects ( a near real time web based MUD ) I wanted a little map window to give visual feedback to the user on where exactly they were. Fortunately the Canvas API makes this stupid easy.
var oX = this.player.x * (this.mMX / this.rMX); var oY = this.player.y * (this.mMX / this.rMY); var halfX = ( this.wMX / 2 ); var halfY = ( this.wMY / 2 ); var startX = Math.max(0, oX - halfX); var startY = Math.max(0, oY - halfY); var endX = Math.max(startX + this.wMX); var endY = Math.max(startY + this.wMY); var buffer = this.ctx.getImageData(startX, startY, endX, endY); this.window.putImageData(buffer, 0, 0);
First block takes the player or avatars position then scales up their grid position to the map canvas position.
Second block gets middle point of the window canvas, in this case if the window is 150×150, the origin is (75,75)
Now given the player’s position in the canvas map it finds the upper left and lower right corners of the map that is going to be copied from the map canvas into the window canvas. The Math.Max’s are there to prevent the upper left corner from being an impossible point (123, -50 ).
The end*’s use of Math.Max is actually crap on my part and isn’t needed.