Skip to content

Instantly share code, notes, and snippets.

@hendrysadrak
Created November 18, 2014 18:04
Show Gist options
  • Save hendrysadrak/85693d301fd3ccadf0b9 to your computer and use it in GitHub Desktop.
Save hendrysadrak/85693d301fd3ccadf0b9 to your computer and use it in GitHub Desktop.

Revisions

  1. Hendry Sadrak created this gist Nov 18, 2014.
    65 changes: 65 additions & 0 deletions Canvas Element - Line
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,65 @@
    var lines = [];

    function Line(x, y, toX, toY, width, color) {
    this.x = x;
    this.y = y;
    this.toX = toX;
    this.toY = toY;
    this.width = width;
    this.color = color;
    this.alpha = 1;
    this.angleRadians = Math.PI + Math.atan2(this.toY - this.y, this.toX - this.x);
    this.angleDeg = this.angleRadians * 180 / Math.PI;

    this.speed = 2;
    this.active = true;
    this.life = 150;
    this.startlife = this.life;

    lines.push(this);

    this.live = function () {
    if (this.life > 0) {
    this.life--;
    } else {
    this.active = false;
    }

    this.distance = getDistance({
    x: this.toX,
    y: this.toY
    }, {
    x: this.x,
    y: this.y
    });
    this.alpha = this.life / this.startlife;

    this.toX += this.speed * Math.cos(this.angleDeg * Math.PI / 180);
    this.toY += this.speed * Math.sin(this.angleDeg * Math.PI / 180);
    };

    this.draw = function () {
    ctx.beginPath();
    ctx.moveTo(this.x, this.y);
    ctx.lineTo(this.toX, this.toY);
    ctx.strokeStyle = this.color;
    ctx.lineWidth = this.width;

    // fade out
    ctx.save();
    ctx.globalAlpha = this.alpha;
    ctx.stroke();
    ctx.restore();
    };
    };

    /*
    Draw Lines
    */

    for (var i in lines) {
    if (lines[i].active) {
    lines[i].live();
    lines[i].draw();
    }
    }