画布大小HTML

Yah*_*hoo 2 html javascript css html5 canvas

我想根据DIV的内容动态调整画布大小.我使用以下代码,但它似乎不起作用.

<canvas id="canvas1" width="800" height="2000"  > <canvas>
Run Code Online (Sandbox Code Playgroud)

使用Javascript

document.getElementById("canvas1").style.height = document.getElementById("div").style.height;
document.getElementById("canvas1").style.width= document.getElementById("div").style.width;
Run Code Online (Sandbox Code Playgroud)

另外我想要画布自动加载,我该怎么做?在一个$(document).ready事件?

我该怎么做?

gbl*_*zex 8

使用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;
}
Run Code Online (Sandbox Code Playgroud)

  • 工作......谢谢:) (2认同)