简体   繁体   English

ctx.addEventListener使画布绘图消失

[英]ctx.addEventListener makes canvas drawing disappear

When I add 当我添加

 ctx.addEventListener('mousedown', onDown, false);

The canvas drawing (background and shapes) disappear and the page is blank, and then when I remove this event listener from the code they reappear again. 画布绘图(背景和形状)消失,页面空白,然后当我从代码中删除此事件侦听器时,它们再次出现。 Just wondering why this is happening? 只想知道为什么会这样? Thanks in advance 提前致谢

<script>


 var ctx, W, H;
 var x = 10;

window.onload = function() {


  var canvas = document.getElementById("canvas");
  W = window.innerWidth;
  H = window.innerHeight;
  canvas.width = W;
  canvas.height = H;


  ctx = canvas.getContext("2d");
  ctx.addEventListener('mousedown', onDown, false); //When this is here, canvas drawing disappears, when it's not here canvas drawing reappears again




  setInterval(draw, 1);


function draw() {
  ctx.globalCompositeOperation = "source-over";
  ctx.fillStyle = "#E6E6FF";
  ctx.fillRect(0, 0, W, H);

  ctx.fillStyle = "black";
  ctx.fillRect(x,20,10,10);
  ctx.font = "30px Arial";
  ctx.fillText("Hello World",10,80);
  ctx.fill();

}


}


function onDown(event) {
    //where x is found
    cx = event.pageX
    cy = event.pageY
    alert("X,Y ="+cx+','+cy);
}

You can't add an event listener to the canvas's context. 您不能将事件侦听器添加到画布的上下文。 You'll need to add it to the canvas itself. 您需要将其添加到画布本身。

Instead of: 代替:

ctx.addEventListener('mousedown', onDown, false);

… do this: … 做这个:

canvas.addEventListener('mousedown', onDown, false);

jsBin demo jsBin演示

use: 采用:

ctx.canvas.addEventListener

or: 要么:

canvas.addEventListener

cause context is just an Object in which the HTMLElementCanvas lives in. 原因context只是HTMLElementCanvas所在的对象。

To spot such errors your-self, the easiest way is to debug your code using Developer Tools, opening the console tab and reading the errors you're shown: 要自行发现此类错误,最简单的方法是使用开发人员工具调试代码,打开控制台标签并阅读显示的错误:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM