简体   繁体   English

我的JavaScript画布代码有什么问题?

[英]Whats wrong with my javascript canvas code?

I wrote this js canvas code. 我写了这个js canvas代码。 It works but it paints half of a canvas angularly. 它可以工作,但可以成角度地绘制一半的画布。 Can I do something to correct this code or I need to fully rewrite it. 我可以做些什么来纠正此代码,还是需要完全重写它。 Is it right to put this code inside setup(). 将此代码放在setup()中是否正确。 Thank you. 谢谢。 https://p5js.org/reference/#/p5/random https://p5js.org/reference/#/p5/random

var side = 10;
var grassArr = [];
var matrix = [];



console.log(matrix)


function setup() {
    for(var y = 0; y<49; y++){
    matrix[y] = [];
    for(var x = 0; x<49; x++){
let arr = [0,1,2]
let r = random(arr)
matrix[x][y] = r
matrix.push(r)    
}
}


frameRate(5)
 createCanvas(49 * side, 49* side);
  background('#acacac');
}


function draw(){
        for (var y = 0; y < 49; y++) {
for (var x = 0; x < 49; x++) {
        if(matrix[y][x]== 0){
                fill('#acacac')
                rect(x * side, y * side, side, side);
            }
                if(matrix[y][x]== 1){
                fill('green')
                rect(x * side, y * side, side, side);
            }
            if(matrix[y][x]== 2){
                fill('yellow');
                  rect(x * side, y * side, side, side);

            }
        } 
     }
}

You just have a small error on the matrix construction. 您在矩阵构造上只有一个小错误。 Here, corrected it for you. 在这里,为您更正。

 var side = 10; var grassArr = []; var matrix = []; function setup() { for(var y = 0; y<49; y++){ matrix[y] = []; for(var x = 0; x<49; x++){ let arr = [0,1,2] let r = random(arr) matrix[y][x] = r; } } frameRate(5) createCanvas(49 * side, 49* side); background('#acacac'); } function draw(){ for (var y = 0; y < 49; y++) { for (var x = 0; x < 49; x++) { if(matrix[y][x]== 0){ fill('#acacac') rect(x * side, y * side, side, side); } if(matrix[y][x]== 1){ fill('green') rect(x * side, y * side, side, side); } if(matrix[y][x]== 2){ fill('yellow'); rect(x * side, y * side, side, side); } } } } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"></script> 

You were inverting x and y variables in the matrix creation and calling .push again which generated lots of undefined places in the matrix. 您正在转换矩阵创建中的x和y变量,然后再次调用.push,这会在矩阵中生成许多未定义的位置。

If you want just call console.log(matrix) after matrix creation using your code version and you'll see lots of undefined values. 如果您只想在使用代码版本的矩阵创建后调用console.log(matrix),就会看到很多未定义的值。

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

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