How to create in HTML5 canvas viewport? something like for tile maps.

  • 3
    \$\begingroup\$ Can you please elaborate a little? your question is vague or incomplete and cannot be answered in it's current state. \$\endgroup\$ – rlemon May 15 '12 at 16:07
  • \$\begingroup\$ Indeed, you need to elaborate. I bet you want something more than just <canvas />. \$\endgroup\$ – Laurent Couvidou May 15 '12 at 17:38
  • \$\begingroup\$ I took the assumption you just want the canvas to fit the entire screen... accommodating for resize. check answer below, if that was the wrong assumption then correct me and i'll revise my answer. cheers. \$\endgroup\$ – rlemon May 15 '12 at 17:57

Taking a wild stab at what you want I will give you a few ways of doing this:

Pure CSS way... (simplified)


<body><canvas>Canvas not supported</canvas></body>


html, body, canvas {
 height: 100%; width: 100%; padding: 0; margin: 0; 

The JS way


<body><canvas id="cvs">Canvas not supported</canvas></body>


window.onload = function() {
    var cvs = document.getElementById("cvs"),
        height, width;
    this.onresize = function() {
        height = window.innerHeight, width = window.innerWidth;
        cvs.setAttribute("height", height);
        cvs.setAttribute("width", width);
| improve this answer | |

You didn't say whether you're using the 2d context or WebGL; I'll assume that you're using 2d context.

You can use the 2d context object's transformation methods to set the translation.

Normally this means that at the beginning of rendering each frame, you reset the transformation, with a call such as:


Then you transform based on your current viewport, such as:

ctx.translate(- offsetX, - offsetY);

This assumes that you have variables offsetX and offsetY which contain the coordinates of the top-left corner of the viewport.

Then you can just render all objects normally using "World coordinates" and have the outcome you expect.

Culling is left as an exercise for the reader :)

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.