Xlaudius
Xlaudius

Reputation: 1837

HTML5 Canvas fills windows with full resolution

I am trying to achieve a layout like this:

Desired effect

where:

Live example: jsFiddle

I have a problem with Canvas. I currently have a simple style:

<canvas id="le_canvas">Y U NO CANVAS</canvas>
...
#le-canvas {
    position:absolute;
    width:100%;
    height:100%;
}

and the canvas is filling the background, but:

What I'd like (if it is possible):

Upvotes: 0

Views: 706

Answers (2)

user1693593
user1693593

Reputation:

Setting the canvas element in per-centage will not set the actual canvas size which must be set in absolute pixels. What happens here is that you get a canvas with a default size which then is stretched by the html-rendering giving the blurry look.

You therefor need to set the size by using f.ex. the window's sizes in absolute pixels.

You can do this like this (update of fiddle here: http://jsfiddle.net/x5LpA/3/ ) -

Create a function that sets the canvas size based on window size (you will of course need to subtract height of bars etc, but to show the principle):

function initCanvasArea(cnv) {
    cnv.width = window.innerWidth;
    cnv.height = window.innerHeight;
}

As the canvas content are cleared when the canvas is re-sized you need to render the content again for each time. Therefor it will be smart to extract the render content into a separate function like f.ex:

function renderCanvas(ctx) {
    ctx.fillStyle = "rgb(200,0,0)";
    ctx.fillRect(0, 0, 55, 50);

    ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
    ctx.fillRect(20, 20, 55, 50);
}

Now, make the main function a self-invoking one where you also attach an event handler for windo.resize to update the canvas:

$(function () {

    var canvas = $('#le_canvas')[0];
    var ctx = canvas.getContext('2d');

    initCanvasArea(canvas);
    renderCanvas(ctx);

    window.onresize = function(e) {
        initCanvasArea(canvas);
        renderCanvas(ctx);
    };


})();

And finally edit the CSS-rule by removing the width/height set to 100%;

#le_canvas {
    position:absolute;
}

(Tip: a better approach here is to use the fixed attribute for position - plus use a wrapper element, padding, box-sizing.. but that is out of scope for this question).

Upvotes: 1

gaynorvader
gaynorvader

Reputation: 2657

Is this what you are after? I used $(document).width() and $(document).height() to get the width and height for the rectangle. http://jsfiddle.net/x5LpA/1/

Upvotes: 0

Related Questions