Search code examples
javascripthtml5-canvasecmascript-6gsap

ES6 - Canvas stroke not working


i'm trying to do some modifications (in ES6) in this pen http://codepen.io/IMarty/pen/RaajQx, and it's almost perfectly working, except for these function

function drawLines(p) {
    if(!p.active) return;
    for(var i in p.closest) {
        ctx.beginPath();
        ctx.moveTo(p.x, p.y);
        ctx.lineTo(p.closest[i].x, p.closest[i].y);
        ctx.strokeStyle = 'rgba(255,255,255,'+ p.active+')';
        ctx.stroke();
    }
}

In my pen http://codepen.io/wendelnascimento/pen/PzRzGE, i've written everything in ES6 and it's working, but just the strokes aren't showing. The method looks like this

drawLines(p) {
    if(!p.active)
        return;

    for(var i = 0; i < p.closest.length; i++) {
        this._context.beginPath();
        this._context.moveTo(p.x, p.y);
        this._context.lineTo(p.closest[i].x, p.closest[i].y);
        this._context.strokeStyle = `rgba(255,255,255,${p.active})`;
        this._context.stroke();
    }
}

Can anyone help me with this?


Solution

  • This is because your list of closest points has only one element, so the iteration draws no lines. Reason for it: you have

    if(p1 == p2) {
        let placed = false;
    
        for(let k = 0; k < 5; k++) {
            if(!placed) {
                if(!closest[k]) {
                    closest[k] = p2;
                    placed = true;
                }
            }
         }
    }
    

    While it should be:

    if(!(p1 == p2)) {
        let placed = false;
    
        for(let k = 0; k < 5; k++) {
            if(!placed) {
                if(!closest[k]) {
                    closest[k] = p2;
                    placed = true;
                }
            }
         }
    }
    

    You want to enter the above if when points are different.

    This draws lines between points, however the effect is very different to the example you were inspired by. If that's what you wanted - well done; if not, there's probably another problem, like picking mouse position and finding points closest to that, not the origin.