0

I'm looking for a solution to freehand draw a line with a gradient in canvas like this:

enter image description here

I already found this, but the gradient seems to be 'locked' on the background and is not following the line.

window.addEventListener('load', ()=>{
    
resize(); // Resizes the canvas once the window loads
document.addEventListener('mousedown', startPainting);
document.addEventListener('mouseup', stopPainting);
document.addEventListener('mousemove', sketch);
window.addEventListener('resize', resize);
});

const canvas = document.querySelector('#canvas');

const ctx = canvas.getContext('2d');

function resize(){
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
}

let coord = {x:0 , y:0};

let paint = false;

function getPosition(event){
coord.x = event.clientX - canvas.offsetLeft;
coord.y = event.clientY - canvas.offsetTop;
}
function startPainting(event){
paint = true;
getPosition(event);
}

function stopPainting(){
paint = false;
}

function sketch(event){
if (!paint) return;
ctx.beginPath();

ctx.lineWidth = 5;

ctx.lineCap = 'round';

var gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0.00, 'grey');
gradient.addColorStop(1 / 2, 'white');
gradient.addColorStop(1.00, 'grey');

ctx.strokeStyle = gradient;

ctx.moveTo(coord.x, coord.y);

getPosition(event);

ctx.lineTo(coord.x , coord.y);

ctx.stroke();
}

Can somebody help me please?

Alberto Sinigaglia
  • 12,097
  • 2
  • 20
  • 48

1 Answers1

0

I found a way to do it:

var context = canvas.getContext("2d");
context.strokeStyle = '#000000';
context.fillStyle = '#000000';
context.beginPath();
context.moveTo(10, 10);
context.lineTo(50, 10);
context.lineWidth = 2;
context.stroke();

context.beginPath();
context.lineWidth = 15;
context.moveTo(10, 30);
context.lineTo(50, 30);
context.stroke();

context.beginPath();
context.moveTo(10, 50);
context.lineTo(50, 50);
context.lineWidth = 2;
context.stroke();

Where I reconstructed the gradient with multiple lines and a blur on those lines.