HTML中宽度和高度,HTML5中的画布宽度和高度

小编典典

的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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值