【问题标题】:Drawing pipes/tubes using HTML5 canvas使用 HTML5 画布绘制管道/管子
【发布时间】:2012-05-14 03:18:27
【问题描述】:

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

当将合成操作作为异或时,它有点好,但不是那么好。

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>

【问题讨论】:

    标签: javascript html html5-canvas


    【解决方案1】:

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

    【讨论】:

    • 您能否制作一个 fiddle、plunkr 或 codepen 来说明您的解决方案?我正在尝试做同样的事情。谢谢。
    猜你喜欢
    • 2015-06-26
    • 1970-01-01
    • 2011-08-07
    • 2012-12-20
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 2016-08-22
    • 2019-04-12
    相关资源
    最近更新 更多