I\'m painting to a canvas which isn\'t being cleared and making it so that the canvas either fades to a solid colour over time, or fades in alpha revealing the layer behind.
The answers here really helped me to understand the problem. I tried it @Blindman67's way but had issues with the globalCompositeOperation
method as others mentioned.
What I ended up doing is push()
mouse coordinates into an array, and then shift()
the array when the line gets as long as I want the trail to be.
Then, each renderAnimationFrame
I am drawing the set of segments in ascending transparency.
var canvas = document.getElementById('noGhost'),
ctx = canvas.getContext('2d'),
time = 0,
segments = [],
maxLength = 20,
lineColor = {
r: 255,
g: 0,
b: 0
};
//really nice options for hex to rgb here: https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
document.addEventListener('mousemove', function(evt){
segments.push({
x: evt.pageX,
y: evt.pageY,
});
if(segments.length > maxLength) {
segments.shift();
}
}, false);
function render() {
//reset canvas
canvas.width = canvas.width;
if(segments.length > 2) {
for(var i = 1; i < segments.length; i++) {
ctx.beginPath();
ctx.strokeStyle = "rgba(" + lineColor.r + "," + lineColor.g + "," + lineColor.b + "," + (i / segments.length) + ")"
ctx.moveTo(segments[i-1].x, segments[i-1].y);
ctx.lineTo(segments[i].x, segments[i].y);
ctx.stroke();
}
}
//as time goes, shorten the length of the line
time++;
if(time % 2 == 0) {
segments.shift();
}
requestAnimationFrame(render);
};
requestAnimationFrame(render);
#noGhost {
background: silver;
}