4

enter image description here

I am drawing a green line using an array of points.

for(var i = this.trail.length - 1; i > -1 + 1; i--)
{
    var time = this.trail[i][0];
    var pos = this.trail[i][1];
    var pos2 = this.trail[i - 1][1];


    var difference = currentTime - time;

    var alpha = ((falloffTime - difference) / 255.0) / 255.0;

    if(alpha < 0)
        alpha = 0;


    pos = camera.WorldToScreen(pos.x, pos.y);
    pos2 = camera.WorldToScreen(pos2.x, pos2.y);

    con.moveTo(pos.x, pos.y);
    con.lineTo(pos2.x, pos2.y);

    con.lineWidth = 3;
    con.strokeStyle = "rgba(128, 190, 3, " + alpha + ")";
    con.stroke();
}

Currently I am drawing it in a loop so that I can set the alpha.

However, the line that is drawn looks a bit jagged.

I know that if I draw it all as a single line, I can use

con.lineJoin="round";

To make the edges smooth. The issue is that if I draw it all as a single line. I can't have half fade out. Since if I use a gradient, it will only apply to the first single line drawn and not the entire trail.

Example

So my question is. How can I draw a line that has smooth edges and I can make it fade out?

iehrlich
  • 3,572
  • 4
  • 34
  • 43
John
  • 5,942
  • 3
  • 42
  • 79
  • 1
    http://stackoverflow.com/questions/7054272/how-to-draw-smooth-curve-through-n-points-using-javascript-html5-canvas – ibrahim mahrir Apr 20 '17 at 21:23
  • 1
    Second answer will give an array of points, which will allow you to stop and restart your drawings (and hence change the color just like you do). But note that in the given code block you are not calling beginPath, so in your loop you are drawing over the same path chunks over and over. – Kaiido Apr 20 '17 at 23:29

1 Answers1

0

Given the JSFiddle link you provided, I was able to produce what I think you are after. I simply modified the end bounds of the gradient. The original gradient (Line 7) is:

var grad= ctx.createLinearGradient(50, 50, 150, 150);

and this only encompasses the first line segment. However, if I change the latter two parameters, it begins to cross the whole line:

var grad= ctx.createLinearGradient(50, 50, 250, 250);

So assuming you defined your StrokeStyle above the loop and had it encompass the entire length of the line, it should work with the rounded miter (line join).

Hope this helps.

Aaron R.
  • 51
  • 6