HTML5中的画布宽度和高度 [英] Canvas width and height in HTML5
问题描述
是否可以修复HTML5 canvas
元素的宽度和高度?
Is it possible to fix the width and height of an HTML5 canvas
element?
<canvas id="canvas" width="300" height="300"></canvas>
推荐答案
c $ c> DOM元素具有
高度对应的
和 .height
和 .width
属性=... width =...
将其设置为JavaScript代码中的数值,以调整画布大小。例如:
The canvas
DOM element has .height
and .width
properties that correspond to the height="…"
and width="…"
attributes. Set them to numeric values in JavaScript code to resize your canvas. For example:
var canvas = document.getElementsByTagName('canvas')[0];
canvas.width = 800;
canvas.height = 600;
请注意,这将清除画布,但您应该遵循 ctx.clearRect (0,0,ctx.canvas.width,ctx.canvas.height);
来处理那些没有完全清除画布的浏览器。
Note that this clears the canvas, though you should follow with ctx.clearRect( 0, 0, ctx.canvas.width, ctx.canvas.height);
to handle those browsers that don't fully clear the canvas. You'll need to redraw of any content you wanted displayed after the size change.
进一步注意,height和width是用于绘制的逻辑画布尺寸,而< em 与 style.height
和 style.width
CSS属性不同。如果不设置CSS属性,则将使用画布的固有大小作为其显示大小;如果您设置CSS属性,并且它们与画布尺寸不同,则您的内容将在浏览器中缩放。例如:
Note further that the height and width are the logical canvas dimensions used for drawing and are different from the style.height
and style.width
CSS attributes. If you don't set the CSS attributes, the intrinsic size of the canvas will be used as its display size; if you do set the CSS attributes, and they differ from the canvas dimensions, your content will be scaled in the browser. For example:
// 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倍的画布。
See this live example of a canvas that is zoomed in by 4x.
这篇关于HTML5中的画布宽度和高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!