假设我有一个 <canvas>
其中包含一行(使用 lineTo
函数)。
canvas
经常更改他的尺寸(height
和 width
、height
或 width
)。
在 canvas
期间尺寸变化,我想保持相同的视觉线条宽度。
非常感谢。
以下代码段表示当 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>
最佳答案
所以你有几件事情会让你感到奇怪...... Canvas 需要在 CSS 之外调整大小。通过在 css 中设置大小,您可以拉伸(stretch) Canvas 而不是使用它的 native 大小。
通过切换元素的大小来注意差异。
另一件事是,现在它们的大小正确,您在 100px Canvas 之外开始原始点。
进一步阅读:https://www.w3.org/TR/html5/scripting-1.html#attr-canvas-width
这是一个 fiddle ,显示了这里真正发生的事情 - 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>
关于javascript - 如何在调整 Canvas 大小时防止 HTML5 Canvas 线宽发生变化。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36271482/