[英]drawing in canvas with mouse in chrome
我正在尝试使用鼠标在画布上绘制。 我的应用程序在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)
};
}
在上面的代码中,获得了div名为“ Lienzo”的画布中的鼠标坐标。 画布和边框的CSS如下:
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();
}
}
我附上了一个小提琴链接以使其更清晰: 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.