小编典典

HTML5中的画布宽度和高度

html

是否可以固定HTML5 canvas元素的宽度和高度?

通常的方法如下:

<canvas id="canvas" width="300" height="300"></canvas>

阅读 694

收藏
2020-05-10

共1个答案

小编典典

canvasDOM元素具有.height.width对应的属性的height="…"width="…"属性。在JavaScript代码中将它们设置为数值,以调整画布的大小。例如:

var canvas = document.getElementsByTagName('canvas')[0];
canvas.width  = 800;
canvas.height = 600;

请注意,这将清除画布,但是您应该遵循此操作ctx.clearRect( 0, 0, ctx.canvas.width, ctx.canvas.height);来处理那些不能完全清除画布的浏览器。尺寸更改后,您需要重绘要显示的所有内容。

进一步注意的是,高度和宽度是用于绘制逻辑帆布尺寸和是 不同的
距离style.heightstyle.widthCSS属性。如果未设置CSS属性,则画布的固有大小将用作其显示大小;如果您确实设置了CSS属性,并且它们与画布尺寸不同,则将在浏览器中缩放内容。例如:

// Make a canvas that has a blurry pixelated zoom-in
// with each canvas pixel drawn showing as roughly 2x2 on screen
canvas.width  = 400;
canvas.height = 300; 
canvas.style.width  = '800px';
canvas.style.height = '600px';

请参见此实时画布放大4倍的示例。

var c = document.getElementsByTagName('canvas')[0];

var ctx = c.getContext('2d');

ctx.lineWidth   = 1;

ctx.strokeStyle = '#f00';

ctx.fillStyle   = '#eff';



ctx.fillRect(  10.5, 10.5, 20, 20 );

ctx.strokeRect( 10.5, 10.5, 20, 20 );

ctx.fillRect(   40, 10.5, 20, 20 );

ctx.strokeRect( 40, 10.5, 20, 20 );

ctx.fillRect(   70, 10, 20, 20 );

ctx.strokeRect( 70, 10, 20, 20 );



ctx.strokeStyle = '#fff';

ctx.strokeRect( 10.5, 10.5, 20, 20 );

ctx.strokeRect( 40, 10.5, 20, 20 );

ctx.strokeRect( 70, 10, 20, 20 );


body { background:#eee; margin:1em; text-align:center }

canvas { background:#fff; border:1px solid #ccc; width:400px; height:160px }


<canvas width="100" height="40"></canvas>

<p>Showing that re-drawing the same antialiased lines does not obliterate old antialiased lines.</p>
2020-05-10