キャンバスに矢印で線を引く方法は?



How Draw Line With An Arrow Canvas



言うまでもありませんが、コード上で直接~~~

window.onload = function(){ var cavParam = {} cavParam.canvas = document.getElementById('canvasId') cavParam.ctx = cavParam.canvas.getContext('2d') drawLineArrow(cavParam, 100, 300, 200, 200, '#a3a3a3') } /** * Draw a line with an arrow * @param cavParam canvas canvas variable * @param fromX/fromY starting point coordinates * @param toX/toY endpoint coordinates * @param color line and arrow color **/ function drawLineArrow(cavParam, fromX, fromY, toX, toY, color) { var headlen = 10/ / Customize the length of the arrow line var theta = 45/ / Customize the angle between the arrow line and the line, personally feel that 45 ° is just right var arrowX, arrowY//Arrow line end point coordinates / / Calculate the angle of each angle and the corresponding arrow end point var angle = Math.atan2(fromY - toY, fromX - toX) * 180 / Math.PI var angle1 = (angle + theta) * Math.PI / 180 var angle2 = (angle - theta) * Math.PI / 180 var topX = headlen * Math.cos(angle1) var topY = headlen * Math.sin(angle1) var botX = headlen * Math.cos(angle2) var botY = headlen * Math.sin(angle2) cavParam.ctx.beginPath() // draw a straight line cavParam.ctx.moveTo(fromX, fromY) cavParam.ctx.lineTo(toX, toY) arrowX = toX + topX arrowY = toY + topY //Draw the upper arrow line cavParam.ctx.moveTo(arrowX, arrowY) cavParam.ctx.lineTo(toX, toY) arrowX = toX + botX arrowY = toY + botY //Draw the arrow line below cavParam.ctx.lineTo(arrowX, arrowY) cavParam.ctx.strokeStyle = color cavParam.ctx.stroke() }