You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML5 Canvas:如何计算坐标实现支持lineWidth配置的条纹图案?

解决Canvas可配置宽度的规整条纹图案问题

核心问题在于Canvas线条是居中绘制的,固定坐标无法适配不同的lineWidth,导致重复图案错位。要实现规整条纹,需根据线条宽度动态计算路径坐标,确保图案单元重复时无缝衔接。

关键调整思路

  • 计算线条半宽:线条的一半宽度分布在路径两侧,用lineWidth / 2修正坐标,避免线条超出图案单元或错位。
  • 适配图案单元尺寸:斜条纹的重复单元尺寸需与线条宽度匹配,确保相邻单元的线条能完美衔接。
  • 延伸路径范围:让路径超出图案单元边缘一点,保证线条在单元内的部分完整,重复时不会出现断裂。

修改后的代码

function createStrippedPattern(color, lineWidth = 5) {
  const pattern = document.createElement('canvas');
  const halfWidth = lineWidth / 2;
  // 图案单元尺寸:线条宽度 + 间隔(此处间隔等于线条宽度,可自定义)
  const unitSize = lineWidth * 2;
  pattern.width = unitSize;
  pattern.height = unitSize;

  const context = pattern.getContext('2d');
  context.strokeStyle = color;
  context.lineWidth = lineWidth;
  context.imageSmoothingEnabled = false; // 关闭抗锯齿,避免模糊

  // 绘制斜条纹:路径延伸到单元外,确保线条居中且重复衔接
  context.beginPath();
  context.moveTo(-halfWidth, -halfWidth);
  context.lineTo(unitSize + halfWidth, unitSize + halfWidth);
  context.stroke();

  return context.createPattern(pattern, 'repeat');
};

function fillWithPattern(targetCanvas, pattern) {
  const ctx = targetCanvas.getContext('2d', {
    antialias: false
  });
  const width = targetCanvas.width;
  const height = targetCanvas.height;
  ctx.fillStyle = pattern;
  ctx.fillRect(0, 0, width, height);
  return targetCanvas;
}

// 使用示例:传入颜色和线条宽度
fillWithPattern(
  document.getElementById("targetCanvas"),
  createStrippedPattern("red", 5)
);
<canvas id="targetCanvas" width="30" height="30"></canvas>

代码说明

  • 动态半宽计算:halfWidth = lineWidth / 2 用来调整路径起点和终点,确保线条居中绘制在单元对角线上。
  • 单元尺寸可定制:unitSize = lineWidth * 2 让条纹和空白区域等宽,若需更宽空白,可改为lineWidth * 3等数值。
  • 路径延伸处理:路径从(-halfWidth, -halfWidth)到(unitSize + halfWidth, unitSize + halfWidth),保证线条边缘刚好覆盖单元四角,重复时相邻单元线条完全衔接,不会出现混乱。

如果需要其他角度的条纹,只需调整路径斜率。比如绘制135度条纹,可将路径改为从(-halfWidth, unitSize + halfWidth)到(unitSize + halfWidth, -halfWidth)。

内容的提问来源于stack exchange,提问作者Oxy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 17:25:27