undefined属性调用一个对象,检测鼠标是否在文本上

时间:2018-04-22 09:31:57

标签: javascript class properties html5-canvas undefined

试图在mousemove事件中调用一个函数来检测鼠标是否在文本上面我是否获得了错误

palabraInestable.js:126 Uncaught TypeError:无法读取属性' posX'未定义的     at contains(palabraInestable.js:126)

说对象palInst未定义 但是,palInst是一个声明为通用的对象,可以在所有代码块中加入。 事实上,如果您评论所有与事件相关的事物(对contains()的所有引用),您可以看到 palInst.pintaPalabraInestable() ; 工作,因此palInst是一个工作的对象。 所以,......我做错了什么???

链接到完整代码https://jsfiddle.net/oeL2yq97/29/



// class ///////////
class PalabraInestable {

  constructor(texto, posX, posY) {

    this.texto = texto || "";
    this.posX = posX || 0;
    this.posY = posY || 0;

    this.altoPalabra = 20;
    this.anchoPalabra = 40;
  }

  // metodos ///////////////////////////////////////////////////////////////

  pintaPalabraInestable() {

    ctx.fillText(this.texto, this.posX, this.posY);
  }

  tickle() {

    this.posX += Math.random() * 5 - 3; // un número aleatorio entre -5 y 5
    this.posY += Math.random() * 5 - 3; // un número aleatorio entre -5 y 5

  }

}

//variables universales ----------------------------------------------------------

// posiciones iniciales del texto total
var x = 100;
var y = 200;

delay = 100;


// palabra objeto prueba
var palInst = new PalabraInestable();

//////////////////////////////////////////////////////////////////////////////////

function init() { // setup() mas o menos

  // configuracion del canvas 
  canvas = document.getElementById("papel");
  ctx = canvas.getContext("2d");


  ctx.font = " 45px Amatic SC "; // para todo el canvas
  ctx.textAlign = "left";
  ctx.textBaseline = "middle";

  palInst.texto = "palabra inestable";
  palInst.posX = 100;
  palInst.posY = 100;

  // eventos de raton LLAMADAS A FUNCIONES 
  canvas.addEventListener('mousemove', mouseMove, false);
  //canvas.addEventListener('mousedown', mouseDown, false);
  //canvas.addEventListener('mouseup',   mouseUp,   false);
  //canvas.addEventListener('mouseout',  mouseUp,  false);  
  //canvas.addEventListener('dblclick', doubleClick, false); 


  setInterval(draw, delay); // llama al draw() y fija fotogramas 
} // fin de init ---------------------------------------------------------


function draw() {

  ctx.clearRect(0, 0, canvas.width, canvas.height);

  ctx.save();

  // aqui el follon  

  palInst.pintaPalabraInestable();

  //  restaura el canvas salvado
  ctx.restore();

  requestAnimationFrame(draw); // llamada recursiva al draw
}

requestAnimationFrame(draw); // ejecucion del draw
/**/


// funciones ========================================================================

// ensayo mousemove -------------------------------------------------------------------
function mouseMove(evento, palInst) {
  let mouseX = getMousePosX(canvas, evento);
  let mouseY = getMousePosY(canvas, evento);

  // If mouse is over the word
  if (contains(mouseX, mouseY, palInst)) {
    palInst.tickle(); //     
  }
}


// mouse position separated to be clear -----------------------------------------
function getMousePosX(canvas, evento) {

  let ClientRect = canvas.getBoundingClientRect();
  //console.log("entra en getmouse pos x");
  // devuelve un objeto con las coordenadas x e y
  return Math.round(evento.clientX - ClientRect.left);

}

function getMousePosY(canvas, evento) {

  let ClientRect = canvas.getBoundingClientRect();

  // devuelve un objeto con las coordenadas  y       
  return Math.round(evento.clientY - ClientRect.top);

} //------------------------------------------------------------------------------

// funcion para verificar que pinchamos dentro de un objeto
function contains(mouseX, mouseY, palInst) {
  if ((palInst.posX <= mouseX) && (palInst.posX + palInst.anchoPalabra >= mouseX) && (palInst.posY <= mouseY) && (palInst.posY + palInst.altoPalabra >= mouseY)) {
    return true;
  } else {
    return false;
  }

}
&#13;
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title> mouseover palabra inestable</title>

  <canvas id="papel" width="700" height="700">
	Su navegador no soporta en elemento CANVAS</canvas>

  <style>
    canvas {
      border: 1px solid #bbb;
    }
    
    .subdiv {
      width: 320px;
    }
    
    .text {
      margin: auto;
      width: 290px;
    }
  </style>

</head>

<body onload="init();">

  <script src="scripts/clasePalabraInestable.js"></script>
  <script src="scripts/palabraInestable.js"></script>
  <p align="left" font face="Courier, Arial, Verdana" size="3">
    prueba de palabra inestable
  </p>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

问题:

您的mouseMove函数是一个事件监听器:

canvas.addEventListener('mousemove', mouseMove, false);

因此,当事件发生时,它将仅使用一个参数调用:事件。但它需要两个论点:

function mouseMove(evento, palInst) {

所以第二个(即palInst)将是undefined,并且因为它会遮挡保存您实例的外部palInst,所以:

contains(mouseX, mouseY, palInst);

您可以将undefined作为第三个参数传递。

<强>修正:

mouseMove更改为不期望第二个参数:

function mouseMove(evento) {

注意:

您的代码依赖于许多可能导致更多麻烦的全局变量。我认为你最好考虑重构它,所以它不会。此外,ctx未声明。