[英]ctx.addEventListener makes canvas drawing disappear
当我添加
ctx.addEventListener('mousedown', onDown, false);
画布绘图(背景和形状)消失,页面空白,然后当我从代码中删除此事件侦听器时,它们再次出现。 只想知道为什么会这样? 提前致谢
<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);
}
您不能将事件侦听器添加到画布的上下文。 您需要将其添加到画布本身。
代替:
ctx.addEventListener('mousedown', onDown, false);
… 做这个:
canvas.addEventListener('mousedown', onDown, false);
采用:
ctx.canvas.addEventListener
要么:
canvas.addEventListener
原因context
只是HTMLElementCanvas所在的对象。
要自行发现此类错误,最简单的方法是使用开发人员工具调试代码,打开控制台标签并阅读显示的错误:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.