文章目录
- 直线/弧线 箭头
直线/弧线 箭头
// startX,startY 起始坐标
// endX,endY 结束坐标
// angel 圆弧角度,取值[0,PI]; 0表示画直线箭头,否则画圆弧箭头
CanvasRenderingContext2D.prototype.drawArrow = function(startX,startY,endX,endY,angel){if(startX===endX&&startY===endY){return;}// 备份线条属性const {lineCap:defaultLineCap,lineWidth:defaultLineWidth} = thislet leg = 10;this.lineCap = 'round'if(!angel){ // angel = 0, 画直线// 画长直线this.lineWidth = 2;this.moveTo(startX,startY);this.lineTo(endX,endY);// 计算以结束点为中心点的旋转角度(atan只能返回-PI/2,PI/2,我们需要0,PI)let rotatedRadius = startX==endX?(startY>endY?Math.PI/2:Math.PI*3/2):(Math.atan((endY-startY)/(endX-startX))+(endX>=startX?Math.PI:0));// 计算2个箭头线的端点let x1 = endX+leg*Math.cos(rotatedRadius-Math.PI/4);let y1 = endY+leg*Math.sin(rotatedRadius-Math.PI/4);let x2 = endX+leg*Math.cos(rotatedRadius+Math.PI/4);let y2 = endY+leg*Math.sin(rotatedRadius+Math.PI/4);// 画2个箭头线this.lineWidth = 3;this.moveTo(x1,y1);this.lineTo(endX,endY);this.moveTo(x2,y2);this.lineTo(endX,endY);this.stroke();}else{// 画圆弧// 未完待续// 计算圆弧圆心,半径// 计算箭头端点坐标}// 恢复线条属性this.lineCap = defaultLineCapthis.lineWidth = defaultLineWidth;}
context.drawArrow(257,50,50,133)
context.drawArrow(60,130,60,20)
context.drawArrow(50,50,280,55)
context.drawArrow(280,62,50,60)
此文将持续更新…