小编典典
的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.height和style.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 }
Showing that re-drawing the same antialiased lines does not obliterate old antialiased lines.
2020-05-10