javascript 画布大小 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4768195/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Canvas Size HTML
提问by Yahoo
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.
我想根据 DIV 的内容动态调整画布大小。我正在使用以下代码,但它似乎不起作用。
<canvas id="canvas1" width="800" height="2000"  > <canvas>
Javascript
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).readyevent ?
我也希望画布自动加载,我应该怎么做?参加$(document).ready活动?
How shall i do that too ?
我也要怎么做?
回答by gblazex
Use offsetWidthto get the dimensions of the element (including borders).
使用offsetWidth来获取元素(包括边框)的尺寸。
// 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;
}

