画布在行尾绘制箭头线

时间:2018-06-18 13:38:58

标签: javascript jquery html canvas

我试图在我的行尾创建一个箭头。我有一个起始位置和一个目标位置。画家应该在目标位置绘制两条线,我在那里有一条箭头。

在画布上绘图时,只会绘制线条。没有"箭头"出现。

控制台中没有抛出任何错误。有人能告诉我这里缺少什么吗?



class Position {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

$(document).ready(() => {
  const canvas = $('#canvas')[0];
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  const ctx = canvas.getContext('2d');
  ctx.lineWidth = 1;
  ctx.font = "14px Georgia";
  const arrowLength = 10;

  const startPosition = new Position(50, 50);
  const targetPosition = new Position(200, 200);

  drawLine(ctx, startPosition, targetPosition); // PAINT LINE HERE
  drawArrow(ctx, startPosition, targetPosition, 10); // PAINT ARROW HERE
});

function drawLine(ctx, startPosition, targetPosition) {
  ctx.beginPath();
  ctx.moveTo(startPosition.x, startPosition.y);
  ctx.lineTo(targetPosition.x, targetPosition.y);
  ctx.stroke();
}

function drawArrow(ctx, laneFromPosition, laneToPosition, arrowLength) {
  const targetAngle = Math.atan2(laneToPosition.y - laneFromPosition.y, laneToPosition.x - laneFromPosition.x);

  const tempRad = Math.Pi / 6;
  const radRight = targetAngle - tempRad;
  const radLeft = targetAngle + tempRad;

  const targetPositionRightSideX = laneToPosition.x - arrowLength * Math.cos(radRight);
  const targetPositionRightSideY = laneToPosition.y - arrowLength * Math.sin(radRight);
  drawLine(ctx, laneToPosition, new Position(targetPositionRightSideX, targetPositionRightSideY));

  const targetPositionLeftSideX = laneToPosition.x - arrowLength * Math.cos(radLeft);
  const targetPositionLeftSideY = laneToPosition.y - arrowLength * Math.sin(radLeft);
  drawLine(ctx, laneToPosition, new Position(targetPositionLeftSideX, targetPositionLeftSideY));
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas"></canvas>
&#13;
&#13;
&#13;

0 个答案:

没有答案