在 canvas 中用鼠标在 chrome 中绘图

drawing in canvas with mouse in chrome

我正在尝试使用鼠标绘制 canvas。我的应用程序在 firefox 中运行良好,但我无法在 chrome 中运行。我的代码如下:

function getMousePos(canvas, evt) {
        var rect = canvas.getBoundingClientRect();

        scaleX = canvas.width / rect.width,    /*relationship bitmap vs. element for X*/
        scaleY = canvas.height / rect.height;  /*relationship bitmap vs. element for Y*/
        return {
          x: Math.round((evt.clientX - rect.left)*scaleX),
          y: Math.round((evt.clientY - rect.top)*scaleY)
        };

      }

在上面的代码中,我获取了鼠标坐标,因为 canvas 包含在名为 "Lienzo" 的 div 中。 CSS 对应 canvas 和 lienzo 如下:

canvas {
     image-rendering: -moz-crisp-edges;    /* Firefox */
    image-rendering: pixelated;           /* Chrome */
    position:absolute;
    width:100%;
    height:auto;
    background:white;
    box-shadow: 0 0 10px black;
}

#lienzo {
    position:relative;
    margin-left:1em;
    width:80%;
}

我试图寻找解决方案,但我不能,因为我不太明白哪里出了问题。

我用来用鼠标绘画的代码包含在一个数组中,我在其中按下坐标,当我释放鼠标时,它会打印数组中包含的所有坐标。这是代码片段:

this.mostrarForma= function(){
            for(var i=0; i < lista_de_puntos.length; i++)
              {     
                ctx.strokeStyle=color;
                ctx.lineJoin=tipo;
                ctx.lineWidth=grosor;
                ctx.beginPath();
                //If i am at the begining of the array
                if(lista_de_puntos[i][2] && i){
                    //Entramos aqui si pulsamos y arrastramos
                    ctx.moveTo(lista_de_puntos[i-1][0], lista_de_puntos[i-1][1]);
                 }else{
                    //If I press and I release the button
                    ctx.moveTo(lista_de_puntos[i][0], lista_de_puntos[i][1]);
                 }
                 ctx.lineTo(lista_de_puntos[i][0], lista_de_puntos[i][1]);
                 ctx.closePath();
                 ctx.stroke();
              } 
        }

我附上一个 fiddle link 以使其更清楚: https://jsfiddle.net/ciberlook/rhwcbwwL/18/ 有帮助吗??

我找到了解决办法。在上面的代码中,函数 mostrarForma() 在错误的事件中被触发。这是解决方案:

$('canvas').mousedown(function(e){
    pulsado=true;
    var posX=getMousePos(this,e).x;
    var posY=getMousePos(this,e).y;
        forma.definirForma(posX,posY,false);
        forma.mostrarForma();       

    });

    $('canvas').mousemove(function(e){
        var posX=getMousePos(this,e).x;
        var posY=getMousePos(this,e).y;

        if (pulsado){

            forma.definirForma(posX,posY,true);
            forma.mostrarForma();

        }
    });

    $('canvas').mouseup(function(e){
        pulsado=false; //I release the button

    });

    $('canvas').mouseleave(function(e){
        pulsado=false;
    });
    forma.mostrarForma();