fbpx

23 Mar /The Line Has Been Drawn

Posted by Steve Gilliam

Last week I was working in an Angular2 project. The feature called for us to draw a line on a canvas element.  The gotcha; the line had to fade out like a comet tail and we had maintain visibility of a background image.


Using this Tarik A’s free hand drawing implementation, to capture the points of the line, Greensock to animate the tail, and this bit of code.  We were able to achieve a nice fade out effect.
...

@Component({
  template: `
<div class="container" #container>
              <canvas #canvas></canvas>
              <svg #svg></svg>
            </div>

`
})

...

@ViewChild(‘svg') svg: ElementRef;
svgns = ‘http://www.w3.org/2000/svg';    

createLine(leader, follower) {
        const line = document.createElementNS(this.svgns, 'line');
        
        TweenMax.set(line, { stroke: `#FFFFFF`, strokeWidth: 3, alpha: 1 });
        line.setAttribute('x1', `${follower.x}`);
        line.setAttribute('y1', `${follower.y}`);
        line.setAttribute('x2', `${leader.x}`);
        line.setAttribute('y2', `${leader.y}`);

        this.svg.nativeElement.appendChild(line);        

        // fade out
        TweenMax.to(line, 0.5, { alpha: 0 });
    }

...

TAGS:, ,