javascript - 使用 Javascript lineTo 绘制箭头

标签 javascript canvas

我目前正在尝试在 Canvas 语音气泡元素下绘制一个箭头。

我的问题:

箭头的右侧似乎比左侧长得多。

我尝试过什么:

我尝试通过以下方式创建箭头:

ctx.moveTo(x, y);
ctx.lineTo(30, 30);
ctx.lineTo(50, 10);

这似乎有效,如下所示:https://jsfiddle.net/eefja4kk/1/

但无论我尝试什么,我都无法让它在我当前的代码中工作。我感谢任何形式的帮助和建议。

我当前的代码:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
ctx.font = "12px Helvetica";
var text = 'Speechbubble Speechbubble Speechbubble';
var fontHeight = getTextHeight(text, ctx.font);
component(ctx, ctx.measureText(text).width, fontHeight, "#37f", 10, 10, 16, text);

function component(ctx, width, height, color, x, y, radius, text)
{
   var r = radius;
   var w = width + 40;
   var h = height + 40;
   var pi2 = Math.PI * 2;
   var ap = w * 0.15;
   var aw = 5;
   var ah = 10;

   ctx.beginPath();
   ctx.arc(r, r, r, pi2 * 0.5 , pi2 * 0.75);
   ctx.arc(w - r, r, r, pi2 * 0.75, pi2);
   ctx.arc(w - r, h - r, r, 0, pi2 * 0.25);

   // Speechbubble arrow
   ctx.lineTo(w - ap, h);
   ctx.lineTo(w - (ap * 2), h + ah);
   ctx.lineTo(w - (ap * 2) - (aw * 2), h);

   ctx.arc(r  , h - r, r, pi2 * 0.25, pi2 * 0.5);
   ctx.fillStyle = '#37f';
   ctx.fill();

   // Text fillstyle
   ctx.fillStyle = "#fff";
   ctx.fillText(text, w - ctx.measureText(text).width - 20, h - fontHeight - 10);
}

function getTextHeight(txt, font)
{
   var el = document.createElement('div'), height;
   el.style.cssText = "position:fixed; padding:0; left:-9999px; top:-9999px; font:" + font;
   el.textContent = txt;

   document.body.appendChild(el); 
   height = parseInt(getComputedStyle(el).getPropertyValue('height'), 10);
   document.body.removeChild(el);

   return height;
}
<canvas width="500" height="500" id="canvas"></canvas>

最佳答案

你的计算有误。您可以将其更改为以下内容以使箭头正确:

// Speechbubble arrow
ctx.lineTo(w - ap, h);
ctx.lineTo(w - (ap * 2), h + ah);
ctx.lineTo(w - (ap * 3), h);

Here is a working example


话虽如此,您的变量命名表明这可能不是您想要的。我假设 aw 是箭头宽度,在这种情况下您可以使用:

// Speechbubble arrow
ctx.lineTo(w - ap, h);
ctx.lineTo(w - ap - (aw / 2), h + ah);
ctx.lineTo(w - ap - aw, h);

但我建议您将 aw 更改为更大的值,也许 20as per this example .


如果不确切知道变量要代表什么,很难确定(即 ap 实际意味着什么?在我的示例中,它充当箭头起点的偏移量) ,但你明白了,希望我的解决方案能让你重回正轨。

关于javascript - 使用 Javascript lineTo 绘制箭头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46492007/

相关文章:

javascript - html5 - 绘制多个圆圈 - 每个圆圈填充不同的图像

javascript - Canvas HTML 加载时间

javascript - 访问 HTML 服务表单对象

javascript - 也许是 JavaScript 中的 monad

html - kineticjs (HTML5 Canvas) - 缩小时平滑图像

javascript - 将 highcharts 转换为波斯语图像

html - KineticJS Image Sprite 作为 Canvas 中的工具栏按钮图像

javascript - ngResource 不传递参数 - 如何调试?

javascript - 找不到 Typescript 编译器 : Command "tsc" is not valid

javascript - 使用 jquery 替换选择选项文本