I have a canvas inside of a div, and I want the canvas width to be equal to 90% of the div width.
我在div中有一个画布,我希望画布宽度等于div宽度的90%。
So, for instance:
所以,例如:
<div id="outerDiv" style="height:750px; width:1000px">
<canvas id="myCanvas"></canvas>
</div>
And in the .js file when I initiate the canvas, I have:
在我启动画布的.js文件中,我有:
window.onload = init;
// Main initialization function
function init () {
initCanvas();
registerInputListeners();
iPhoneToTop();
}
// Set up the drawing canvas
function initCanvas () {
canvas = document.getElementById("myCanvas");
// Size canvas
canvas.width = $("#outerDiv").width * .9;
canvas.height = $("#outerDiv").height * .9;
}
This isn't working, and is making the canvas really tiny - 2px by 2px. What am I doing wrong?
这不起作用,并且使画布非常小 - 2px乘2px。我究竟做错了什么?
I tried console logging the width:
我试过控制台记录宽度:
var width = document.getElementById(outerDiv).outerWidth;
console.log(width);
and I get this error : Uncaught TypeError: Cannot read property 'outerWidth' of null
我收到此错误:未捕获TypeError:无法读取null的属性'outerWidth'
1 个解决方案
#1
1
It's #outerDiv
. You forgot the #
. Also I don't think there is width
or height
in a jQuery object (assuming $
is jQuery).
这是#outerDiv。你忘记了#。另外我认为jQuery对象中没有宽度或高度(假设$是jQuery)。
#1
1
It's #outerDiv
. You forgot the #
. Also I don't think there is width
or height
in a jQuery object (assuming $
is jQuery).
这是#outerDiv。你忘记了#。另外我认为jQuery对象中没有宽度或高度(假设$是jQuery)。