Here's a working example fixing the problems:
You had several problems with your example:
- A
<div>
does not have height
or width
attributes. You need to set those through CSS.
- Even if the div were sized correctly, it was using the default
position:static
, which means that it is NOT the positioning parent of any children. If you want the canvas to be the same size as the div, you must set the div to position:relative
(or absolute
or fixed
).
- The
width
and height
attributes on a Canvas specify the number of pixels of data to draw to (like the actual pixels in an image), and are separate from the display size of the canvas. These attributes must be set to integers.
The example linked to above uses CSS to set the div size and make it a positioned parent. It creates a JS function (shown below) to both set a canvas to be the same display size as its positioned parent, and then adjusts the internal width
and height
properties so that is has the same number of pixels as it shows.
var canvas = document.querySelector('canvas');
fitToContainer(canvas);
function fitToContainer(canvas){
// Make it visually fill the positioned parent
canvas.style.width ='100%';
canvas.style.height='100%';
// ...then set the internal size to match
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…