使用 HTML5 画布绘制管道/管道

Drawing pipes/tubes using HTML5 canvas

本文关键字:管道 绘制 HTML5 布绘制 使用      更新时间:2023-09-26

我想用HTML5画布沿着一组点画一个管道/管子。我尝试绘制渐变线,使其看起来像管道,弯曲处的渐变不是连续的。

将组合操作作为 XOR 时,它有点问题,但不是那么好。

var MIDDILE_COLOR = "#ffffff";
var LINE_WIDTH = 20;
window.onload = function() {
  try {
    var context = document.getElementById("abc").getContext("2d");
    var points = [
      [90, 136],
      [101, 21],
      [101, 21],
      [376, 133],
      [100, 300]
    ];
    drawConnectionPipe(context, points, 10, "#ff0000");
  } catch (e) {
    alert(e);
  }
}
function drawConnectionPipe(ctx, coorinateArray, thickness, gradColor) {
  try {
    ctx.save();
    var gradientObject = null;
    //ctx.globalCompositeOperation = 'xor';
    for (var i = 0; i < coorinateArray.length - 1; i++) {
      var startPt = coorinateArray[i];
      var endPt = coorinateArray[i + 1];
      var arr = getPerpendicularPoints(startPt[0], startPt[1], endPt[0], endPt[1]);
      gradientObject = ctx.createLinearGradient(arr[0], arr[1], arr[2], arr[3]);
      gradientObject.addColorStop(0, gradColor);
      gradientObject.addColorStop(0.5, MIDDILE_COLOR);
      gradientObject.addColorStop(1, gradColor);
      ctx.lineWidth = thickness;
      ctx.strokeStyle = gradientObject;
      ctx.lineJoin = "round";
      ctx.beginPath();
      ctx.moveTo(startPt[0], startPt[1]);
      ctx.lineTo(endPt[0], endPt[1]);
      ctx.closePath();
      ctx.stroke();
      //ctx.globalCompositeOperation = 'source-over';
    }
    ctx.restore();
  } catch (e) {
    alert(e);
  }
}
function getPerpendicularPoints(x1, y1, x2, y2) {
  var slantAngle = 0;
  var slant = (x1 - y1) / (x2 - y2);
  slantAngle = Math.PI / 2 - Math.atan2(y2 - y1, x2 - x1);
  var originX = (x1 + x2) / 2;
  var originY = (y1 + y2) / 2;
  var halfDistance = LINE_WIDTH / 2;
  var perpX1 = originX + halfDistance * Math.sin(90 * Math.PI / 180 - slantAngle);
  var perpY1 = originY + halfDistance * -Math.cos(90 * Math.PI / 180 - slantAngle);
  var perpX2 = originX + halfDistance * Math.sin(270 * Math.PI / 180 - slantAngle);
  var perpY2 = originY + halfDistance * -Math.cos(270 * Math.PI / 180 - slantAngle);
  return [perpX1, perpY1, perpX2, perpY2];
}
function getNormalizedAtan2(ydiff, xdiff) {
  var atan2Res = Math.atan2(ydiff, xdiff);
  if (atan2Res < 0) {
    atan2Res += (2 * Math.PI)
  }
  return atan2Res;
}
<html>
<head>
  <title>Raphael Play</title>
</head>
<body>
  <canvas id="abc" width="500" height="500"></canvas>
</body>
</html>

最后,

我使用 svg 过滤器实现了它。在html5画布中,很难创建这样的照明。