繁体   English   中英

重新调整画布大小时如何防止HTML5画布线宽改变。

[英]How to prevent HTML5 canvas line width from changing when re-sizing the canvas.

假设我有一个<canvas> ,其中包含一行(使用lineTo函数)。

canvas会经常更改其尺寸( heightwidthheightwidth )。

canvas尺寸更改期间,我想在视觉上保持相同的线宽。

非常感谢。

以下代码段代表了当画布的尺寸影响线条的视觉宽度时的当前情况。

 var index; var canvas; var context; for (index = 1; index <= 2; index++) { canvas = document.getElementById("canvas" + index); context = canvas.getContext('2d'); context.beginPath(); context.moveTo(100, 150); context.lineTo(450, 50); context.lineWidth = 16; context.stroke(); } 
 <h3> As you can see, both canvas objects has the same line initialization in JavaScript code. the only diff between them are the dimensions (in our case, the width). </h3> <canvas id="canvas1" style="width:100px"></canvas> <canvas id="canvas2" style="width:300"></canvas> 

因此,您可能会觉得有些奇怪……画布需要在CSS之外调整大小。 通过在CSS中设置大小,您可以拉伸画布,而不是使用其本机大小。

通过切换元素的大小来注意差异。

另一件事是,现在它们的尺寸正确了,您是在100px画布之外开始原始点的。

进一步阅读: https : //www.w3.org/TR/html5/scripting-1.html#attr-canvas-width

这是一个小提琴,显示了这里真正发生的事情-https: //jsfiddle.net/bopjtwfe/

 var index; var canvas; var context; for (index = 1; index <= 2; index++) { canvas = document.getElementById("canvas" + index); context = canvas.getContext('2d'); context.beginPath(); context.moveTo(10, 10); context.lineTo(150, 150); context.lineWidth = 16; context.stroke(); } 
 canvas { display: block; margin-bottom: 10px; background-color: white; } 
 <canvas id="canvas1" width='100px' height='100px' ></canvas> <canvas id="canvas2" width='300px' height='300px'></canvas> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM