html画布绘制线条宽度,HTML 5中画布的宽度和高度

这篇博客讨论了如何通过JavaScript动态调整HTML5 canvas元素的width和height属性以改变画布大小,以及这对内容绘制和浏览器缩放的影响。示例代码展示了如何在缩放画布后重新绘制内容,以及当CSS样式与canvas尺寸不同时可能出现的像素渲染问题。同时,提到了重新绘制对于抗锯齿线条的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个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 screencanvas.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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值