编辑:
这是一个Vue组件,带有一个绘制网格的画布,该画布具有附加的EventListener,并this.grid
存储用户单击的位置(在画布内部)。在里面this.grid
init(){
console.log("init this.grid")
//here grid is get from data() and inicialized
this.grid = []
var row = [];
var row2 = []
for(var i=0;i<this.SIZE;i++){
row.push(0);
}
for( i=0;i<this.HEIGHT;i++){
row2.push(row);
}
for( i=0;i<this.SIZE;i++){
this.grid.push(row2);
}
console.log("this.grid 0s")
console.log(this.grid);
var canvas = document.getElementById("canvasDraw");
this.rect = canvas.getBoundingClientRect();
this.ctx = canvas.getContext("2d");
this.ctx.fillStyle = "white";
this.ctx.fill();
for (i=0; i <= this.SIZE*this.big; i += this.big) {
this.ctx.moveTo(0,i);
this.ctx.lineTo(this.SIZE*this.big,i);
this.ctx.stroke();
}
for (i=0; i <= this.SIZE*this.big; i += this.big) {
//ctx.lineWidth(3);
this.ctx.moveTo(i,0);
this.ctx.lineTo(i,this.SIZE*this.big);
this.ctx.stroke();
}
canvas.addEventListener('click',this.write,false);
},
这是write()函数,它写入 this.grid
write(evt){
var x = Math.floor((evt.clientX - this.rect.left)/this.big);
var y = Math.floor((evt.clientY- this.rect.top)/this.big);
console.log("write(evt) call, check if");
console.log(this.grid[x][this.h][y] == 0);
console.log("Old value: "+this.grid[x][this.h][y]);
if(this.grid[x][this.h][y] == 0){
this.grid[x][this.h][y] = 1
}else{
this.grid[x][this.h][y] = 0;
}
console.log("New value: "+this.grid[x][this.h][y]);
console.log(this.grid)
this.posUpdated += "posicion xhy: "+x+" "+this.h+" "+y+"<br/>";
this.ctx.beginPath();
this.ctx.rect((x*this.big), (y*this.big), this.big, this.big);
this.ctx.fillStyle = (this.grid[x][this.h][y] == 1)? "white": "black" ;
this.ctx.fill();
//console.log(this.grid)
//alert((evt.clientX%this.big) + ',' + evt.clientY%this.big);
}
this.grid
是一个用零初始化的3d数组。然后我想将1分配给position(2,0,2)(x,h,y),但是这段代码将1分配给this.grid
它,就像
但是有些方法,现在x == 2的所有位置都分配给1。为什么?我只希望(2,0,2)为1,而不是所有位置(2,h,y)。它应该很简单,但是..谢谢!
我认为问题是在创建3d数组时。您可能使用了fill,该fill将引用同一数组,因此结果将是您所显示的。
这是一个工作示例:
const size = 5
const fill = 0
const arr = new Array(size).fill(0).map(() => new Array(size).fill(0).map(() => new Array(size).fill(fill)))
arr[0][0][0] = 1
console.info(arr)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句