javascript - 如何在调整 Canvas 大小时防止 HTML5 Canvas 线宽发生变化。

标签 javascript html canvas

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

canvas经常更改他的尺寸(heightwidthheightwidth)。

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/

相关文章:

javascript - NodeJS 将数据从当前页面传递到另一个页面

javascript - 为什么我的脚本没有在 div 中动态显示输入字符

html - Perl解析html后出现未初始化值错误

javascript - Javascript 3D 图像处理库

android - Canvas 剪裁矩形 - 包括右/底边?

javascript - Next.js 上使用 Tailwind 的图像重叠导航栏

javascript - Bootstrap 4 使用切换按钮连接侧面菜单(响应式)

html - 如何在悬停时有不同的背景动画时始终显示文本?

javascript - 如何在 HTML 中使我的列动态化

javascript - HTML Canvas 。我的图像只有一半被翻转