samedi 4 juin 2016

Losing value while instancing new object? Javascript

So, I'm trying to draw lines in HTML Canvas using Javascript and I've been trying for a while to identify why my code isn't working.

So overall how it's supposed to work: Event Listener to 'mousedown' starts the process, creates the object in 'createLine' function and update it's dimensions and orientation in the event 'mousemove'. When I let go (meaning the event mouseup) the object is done and pushed into an array (again on the function 'createLine').

What's happening: I've watched the values all over (mouse positions) and it seems that they disappear whenever I create the object. And it's never shown on screen. But they are stored on the 'figures' array but in both beggining and ending positions on the same place.

See code Below:

//Line class
function Linha(_pointIn, _pointFin){
    this.pointIn  = _pointIn    || new Ponto()
    this.pointFin = _pointFin   || new Ponto()
    this.name = 'Linha'
    this.color = 'black'
    this.isDrawing = true
}

Linha.prototype.draw = function(canvas, context){
    context.beginPath()
    context.strokeStyle = this.color
    context.lineWidth = '1'
    context.moveTo(this.pointIn.x, this.pointIn.y)
    context.lineTo(this.pointFin.x, this.pointFin.y)
    context.stroke()
}


canvas.addEventListener('mousemove', function(e){
    mouse.x = e.pageX - this.offsetLeft
    mouse.y = e.pageY - this.offsetTop

    clearCanvas()
    for(i=0; i<figures.length; i++){
        figures[i].draw(canvas, ctx)
    }

    if(isDrawing == 1 && tempFigure != undefined){
        if(tempFigure.name == 'Linha')
            tempFigure.pointFin = mouse
        tempFigure.draw(canvas, ctx)
    }
}, false)


canvas.addEventListener('mousedown', function(e){
    isDrawing = 1
    click1 = getClicks()

    if(isDrawing == 1){
    click1 = getClicks()
    click2 = getClicks()
    createLine(click1, click2)
    }
}, false)

canvas.addEventListener('mouseup', function(e){
    isDrawing = 0
    click2 = getClicks()
    if(tempFigure.name == 'Linha')
    createLine(click1, click2)
}, false)


function createLine(click1, click2){
    if(isDrawing==1){
        tempFigure = new Linha(click1, click2)
    }else{
        figures.push(tempFigure)
        resetVariables()
    }
}




Aucun commentaire:

Enregistrer un commentaire