实例化新对象时失去价值

时间:2016-06-04 21:01:10

标签: javascript canvas web

我尝试使用Javascript在HTML Canvas中绘制线条。

总的来说它应该如何工作: 事件倾听者' mousedown'启动流程,在' createLine'中创建对象。功能和更新它的尺寸和方向在事件' mousemove'。当我放手(意味着事件鼠标)时,对象完成并被推入一个数组(再次在函数' createLine')。

发生了什么: 我已经观察了全部的值(鼠标位置),看起来每当我创建对象时它们就会消失。而且它从未在屏幕上显示过。但它们存储在“数字”中。数组,但在同一个地方的开始和结束位置。

见下面的代码:

function Ponto (_mouse){
    this.x = _mouse.x
    this.y = _mouse.y
    this.id = 'Ponto'
    this.color = 'black'
    this.clicks = 1
}

Ponto.prototype.draw = function(canvas, context){
    context.beginPath()
    context.rect(this.x, this.y, 1, 1)
    context.stroke()
}

//Line class
function Linha(_pointIn, _pointFin){
    this.pointIn  = _pointIn
    this.pointFin = _pointFin
    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()
}

function getClicks(){
    return mouse    
}

var canvas    = document.getElementById('canvasCG')
var ctx       = canvas.getContext('2d')
ctx.lineWidth = 1

var figures = new Array()
var click1  = undefined
var click2  = undefined

var tempFigure = undefined
var isDrawing  = 0

var mouse = {x:0, y:0}

function clearCanvas(){
    ctx.fillStyle = 'rgba(255, 255, 255, 0)'
    ctx.fillRect = (0, 0, canvas.width, canvas.height)
}

function resetVariables(){
    click1 = undefined
    click2 = undefined
    tempFig = undefined
    isDrawing = 0
}

//Mouse Move event
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()
    }
}

0 个答案:

没有答案