一次更改导致canvas事件不监听的奇怪情况



我开始重写Windows!下面的代码绘制了10个可以移动的画布对象。我让它们随机大小。当你点击其中一个时,它有更粗的轮廓,可以到处拖动。

当我添加一行来改变画布的初始顶部位置时,移动停止工作。这很奇怪,我只想以增加10px的步骤堆叠窗口,而不是它们都从同一个位置开始。为什么这个小小的改变会阻止其他的工作呢?

var n = 0,
canv = [],
ct = []
var body = document.getElementsByTagName("body")[0];
var targ, wind = 10,
i, offx, offy = 0
for (n = 0; n < wind; n++) {
canv[n] = document.createElement('canvas');
canv[n].id = "C" + n;
canv[n].width = rnd(30 * n);
canv[n].height = rnd(30 * n);
//canv[n].style.top=10*n     <- This line stops the drag effect working
canv[n].style.zIndex = n;
canv[n].style.position = "absolute";
canv[n].style.border = "2px solid";
body.appendChild(canv[n]);
targ=canv[0]    // added now to stop errors before first click
ct[n] = canv[n].getContext("2d");
ct[n].fillText(n, canv[n].width / 2, canv[n].height / 2)
canv[n].addEventListener('mousedown', function(e) {
targ = e.currentTarget
if (targ.style.border == "2px solid") {
for (i = 0; i < wind; i++) {
canv[i].style.border = "2px solid"
}
targ.style.border = "5px solid";
offy = e.y - targ.style.top
} else {
targ.style.border = "2px solid"
}
});
canv[n].addEventListener('mousemove', function(e) {
if (targ.style.border == "5px solid") {
move(e.x, e.y)
}
});
}
function move(x, y) {
targ.style.top = y - offy
}
function rnd(m) {
return Math.floor(Math.random() * m)
}

您正在使用一个全局变量来决定它何时处于活动状态。这在点击发生之前是不会设置的,所以你会得到大量的错误。

当你设置一个位置时,它需要一些单位。

基本思想与代码清理了一点。

const canv = [];
const ct = [];
const body = document.getElementsByTagName("body")[0];
let targ, wind = 10,
i, offx, offy = 0;
for (let n = 0; n < wind; n++) {
const canvas = document.createElement('canvas');
canv[n] = canvas;

canvas.id = "C" + n;
const width = rnd(30 * n);
const height = rnd(30 * n);

canvas.style.width = width + "px";
canvas.style.height = height + "px";
canvas.style.top = (10 * n) + "px";
canvas.style.left = (10 * n) + "px";
canvas.style.zIndex = n;

body.appendChild(canvas);
const ctx = canvas.getContext("2d");
ct[n] = ctx;
ctx.fillText(n, width / 2, height / 2)
canvas.addEventListener('mousedown', function(e) {
document.querySelectorAll("canvas.active").forEach(elem => {
elem.classList.remove("active");
});
targ = e.currentTarget;
targ.classList.add("active");
});
canvas.addEventListener('mousemove', function(e) {
if (targ && targ.classList.contains('active')) {
move(e.x, e.y)
}
});
}
function move(x, y) {
targ.style.top = y - offy + "px"
}
function rnd(m) {
return Math.floor(Math.random() * m)
}
canvas {
position: absolute;
min-width: 30px;
min-height: 30px;
border: 2px solid black;
z-index: 1;
}
canvas.active {
border: 5px solid black;
}

最新更新