JSFiddle - React, Tailwind, and code Playground

by davorpeic

HTML

<div>
<canvas id="canvasId" width="500" height="500" style="border: 1px solid #ccc;"></canvas>
</div>

CSS

div {
  width: 500px;
  height: 500px;
}

JavaScript

window.onload = function(){
    var cavParam = {};
    cavParam.canvas = document.getElementById("canvasId");
    cavParam.ctx = cavParam.canvas.getContext('2d');
    cavParam.ctx.transform(1, 0, 0, -1, 0, cavParam.canvas.height)
    drawLineArrow(cavParam, 100, 300, 200, 200, "#a3a3a3");
    drawLineArrow(cavParam, 0, 0, 150, 150, "#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.lineWidth = 2;
    cavParam.ctx.stroke();
}