繁体   English   中英

使用 Javascript lineTo 绘制箭头

[英]Draw arrow using Javascript lineTo

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

我的问题:

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

我试过什么:

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

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);

这是一个工作示例


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

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

但是我建议您然后将aw更改为更大的值,例如20如本例所示


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM