var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');
function distance( a, b ) {
return Math.sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) );
}
function drawGradientLine( line_width, grad_1, grad_2, xy1, xy2, underline ) {
var grad = ctx.createLinearGradient(xy1.x, xy1.y, xy2.x, xy2.y);
grad.addColorStop(0, grad_1);
grad.addColorStop(1, grad_2);
ctx.save();
ctx.lineWidth = line_width;
ctx.strokeStyle = grad;
ctx.beginPath();
ctx.moveTo(xy1.x, xy1.y);
ctx.lineTo(xy2.x, xy2.y);
ctx.stroke();
ctx.restore();
if ( underline ) {
const linelen = distance( xy1, xy2);
const hyp1 = line_width / 2;
const angle = Math.asin( (xy2.y - xy1.y) / (linelen) );
const dy = (angle < 0) ? -1 * hyp1 * Math.cos( angle ) : hyp1 * Math.cos( angle );
const dx = (angle < 0) ? -1 * hyp1 * Math.sin( angle ) : hyp1 * Math.sin( angle );
const c1 = {
x: xy1.x - dx,
y: xy1.y + dy
};
const c2 = {
x:xy2.x - dx,
y: xy2.y + dy
};
ctx.save();
ctx.lineWidth = 1;
ctx.strokeStyle = 'black';
ctx.beginPath();
ctx.moveTo(c1.x, c1.y);
ctx.lineTo(c2.x, c2.y);
ctx.stroke();
ctx.restore();
}
}
drawGradientLine( 20, 'red', 'green', {x:50, y: 150}, {x:150, y:150}, true);
drawGradientLine( 20, 'pink', 'orange', {x:10, y: 10}, {x:50, y:50}, true);
drawGradientLine( 20, 'pink', 'orange', {x:200, y: 100}, {x:250, y:20}, true);
drawGradientLine( 10, 'blue', 'green', {x: 50, y: 350}, {x:150, y:450}, false);
drawGradientLine( 40, 'pink', 'aquamarine', {x: 100, y: 200}, {x: 150, y:350}, false);
<canvas id=canvas1 width=300 height=600></canvas>