mercredi 7 novembre 2018

Html Canvas random start position to move afterwards

I am currently learning JavaScript. My english is not very good either.

I want the random start position of the cube to go up and down. This will cause the cubes to jump up and down on the Y axis.

maybe like that:

Y = Y + speed;
if(Y <= 0) {
    speed = -speed;
}
if(Y >= canvas.width) {
    speed = -speed;
}

So that's my code:

window.onload = function() {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
draw();
}
function draw(){
    canvasContext.fillStyle = "white";
    canvasContext.fillRect(0,0,canvas.width,canvas.height, "#cc33ff");
    for (var i=0; i <= 50; i++) {
        var randX = Math.floor(Math.random() * 800);
        X = randX;
        var randY = Math.floor(Math.random() * 600);
        Y = randY;
        speed = 10;
        var colorArray = ['#2185C5', '#7ECEFD', '#FFF6E5', '#FF6666'];    
        var randColor = colorArray[Math.floor(Math.random() * colorArray.length)];    
        canvasContext.beginPath();
        canvasContext.rect(X, Y, 20, 20);   
        canvasContext.fillStyle = randColor;
        canvasContext.fill();
        canvasContext.strokeStyle = "black";
        canvasContext.stroke();
        canvasContext.closePath();
    }
}




Aucun commentaire:

Enregistrer un commentaire