javascript - 在 Canvas 标签上绘制箭头

标签 javascript html5-canvas drawing

我想使用 canvas 标签,javascript 绘制一个箭头。我已经使用二次函数实现了它,但是我在计算箭头的旋转 Angular 时遇到了问题...

有人知道这件事吗?

谢谢

最佳答案

尽可能简单。您必须自己添加 context.beginPath() 和附加 context.stroke() :

ctx = document.getElementById("c").getContext("2d");
ctx.beginPath();
canvas_arrow(ctx, 10, 30, 200, 150);
canvas_arrow(ctx, 100, 200, 400, 50);
canvas_arrow(ctx, 200, 30, 10, 150);
canvas_arrow(ctx, 400, 200, 100, 50);
ctx.stroke();


function canvas_arrow(context, fromx, fromy, tox, toy) {
  var headlen = 10; // length of head in pixels
  var dx = tox - fromx;
  var dy = toy - fromy;
  var angle = Math.atan2(dy, dx);
  context.moveTo(fromx, fromy);
  context.lineTo(tox, toy);
  context.lineTo(tox - headlen * Math.cos(angle - Math.PI / 6), toy - headlen * Math.sin(angle - Math.PI / 6));
  context.moveTo(tox, toy);
  context.lineTo(tox - headlen * Math.cos(angle + Math.PI / 6), toy - headlen * Math.sin(angle + Math.PI / 6));
}
<html>

<body>
  <canvas id="c" width="500" height="500"></canvas>


</body>

关于javascript - 在 Canvas 标签上绘制箭头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/808826/

相关文章:

javascript - 通过 ASPX 响应写入 JSON 时的 IE 错误

javascript - 我的 React 组件是否被重新创建而不是更新?

javascript - 只有在我在 javascript 中更改了 2 个下拉列表后,如何将按钮设置为可见

javascript - 尽管我可以在控制台上看到 Blob 图像,但它不会显示在 UI 上

javascript - 在保持均匀速度的同时通过 Canvas 上的一系列点为对象设置动画?

css - 调整 Canvas 大小 onclick 按钮

java - 使用Java绘图: Applying Borders/Outlines to Shapes

Javascript for-in 循环问题

java - java中文本到图像的定位

java - 如何在 Java Swing 中在两点之间拖动和绘制线