2017-09-29 100 views
2

我目前正试图在我的画布语音泡泡元素下绘制一个箭头。使用Javascript线绘制箭头至

我的问题:

箭头的右侧似乎是路不再那么左侧。

有什么我想:

我试图创建下列方式箭头:这似乎工作,因为在这里可以看到

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>

回答

2

你的计算是关闭。你可以把它改成下面让箭头是正确的:

// 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真正意思是什么?在我的例子中它充当偏移的箭头开始),但你得到的想法,希望我的解决方案让你回到正轨。

+0

第二个是我一直试图归档的确切结果!非常感谢。 – dane