中的画布宽度和高度

中的画布宽度和高度

本文介绍了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>

推荐答案

canvas DOM 元素具有 .height.width 属性对应于 height="..."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); 来处理那些没有的浏览器t 完全清除画布.您需要重绘大小更改后想要显示的任何内容.

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.

进一步注意高度和宽度是用于绘图的逻辑画布尺寸,与style.heightstyle.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.

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>

这篇关于HTML5 中的画布宽度和高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 00:13