0

I wrote this js canvas code. 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(). Thank you. 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);

            }
        } 
     }
}
0

1 Answer 1

1

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.

If you want just call console.log(matrix) after matrix creation using your code version and you'll see lots of undefined values.

Sign up to request clarification or add additional context in comments.

1 Comment

No problem. Glad I could help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.