0

我想使用 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>

4

1 回答 1

1

最后我使用svg filters实现了它。在 html5 画布中创建这样的照明非常困难。

于 2012-06-14T06:47:46.790 回答