Canvas Size HTML

12,176

Use offsetWidth to get the dimensions of the element (including borders).

// loaded automatically on page load
window.onload = function() {
    var div = document.getElementById("div");
    var canvas = document.getElementById("canvas1");
    canvas.height = div.offsetHeight;
    canvas.width  = div.offsetWidth;
}
Share:
12,176
Yahoo
Author by

Yahoo

Updated on June 04, 2022

Comments

  • Yahoo
    Yahoo almost 2 years

    I want to dynamically resize the canvas size according to the content of a DIV. i am using the following Code but it doesn't seems to work.

    <canvas id="canvas1" width="800" height="2000"  > <canvas>
    

    Javascript

    document.getElementById("canvas1").style.height = document.getElementById("div").style.height;
    document.getElementById("canvas1").style.width= document.getElementById("div").style.width;
    

    Also i want that the canvas is loaded automatically , How should i do that ? on a $(document).ready event ?

    How shall i do that too ?

  • Yahoo
    Yahoo over 13 years
    It works Great, but the image which is already there on the canvas gets Pixelated , the image also expands. i want that the size of the image which is drawn on the canvas remains unchanged
  • Phrogz
    Phrogz over 13 years
    @AdiMathur Then change the .width/height of the canvas; you'll also need to redraw the contents then.
  • Yahoo
    Yahoo over 13 years
    I am ready to draw again but the statement dosnt work.... canvas.height = div.offsetHeight + "px"; canvas.width = div.offsetWidth + "px";
  • Yahoo
    Yahoo over 13 years
    i want the drawing ratio to the canvas be 1 : 1
  • gblazex
    gblazex over 13 years
    @Adi - Alright I didn't know about images. CSS dimensions are not good then. You should use width/height but without px. See my update.