[英]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.