wubbewubbewubbe
wubbewubbewubbe

Reputation: 741

Canvas not resized properly to div (scroll bar issue??)

I don't know if anybody ever noticed this, but I'll give it a try.

Because the canvas behaves differently from other HTML elements, I use the resize event to resize it rather than CSS. This works well,

except when the browser is resized from maximized to normal, in which case the canvas is smaller than the div. The difference is about

the width of a scrollbar. In fact, when I make the canvas big enough to enforce a scrollbar, this doen't happen.

Has this anything to do with timing of the resize event? Does anybody know how to solve it?

edit

This is true for IE9 (right side) and Safari (bottom and right side). But not for Chrome and FF.

fiddle over here -> fiddle

/edit

window.onload = function()
{
    canvas = document.getElementById("canvas");
    context = canvas.getContext("2d");
    window.addEventListener('resize', doTheResize, false);
}

function doTheResize()
{
    canvas.width = div.clientWidth;
    canvas.height = div.clientHeight;
    drawThings();
}

Upvotes: 0

Views: 1606

Answers (1)

Loktar
Loktar

Reputation: 35309

Use getBoundingClientRect to get the width and height and make the canvas that size.

Live Demo

Full Screen

Markup

<div class="container">
    <canvas id="canvas"></canvas>
</div>

CSS

html, body {
    width:100%;
    height:100%;
    padding:0;
    margin:0;
}
.container {
    height:100%;
    width:600px;
}

JS

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");

canvas.width = canvas.parentNode.getBoundingClientRect().width;
canvas.height = canvas.parentNode.getBoundingClientRect().height;

ctx.fillRect(0, 0, canvas.width, canvas.height);

window.onresize = function () {
    canvas.width = canvas.parentNode.getBoundingClientRect().width;
    canvas.height = canvas.parentNode.getBoundingClientRect().height;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
}

Upvotes: 2

Related Questions