dimanche 15 octobre 2017

store a value from a random generator

I'm still new to javascript. I'm working on an javascript tutorial from here http://ift.tt/2zadkrr One of the more challenging exercise is to make the ball change color when it bounce off from a wall. So far i manage to do this:

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
var ballRadius = 10;

function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

function ballColor(){
    var newColor = getRandomColor();
    return newColor;
}

function drawBall(){
    ctx.beginPath();
    ctx.arc(x, y, ballRadius, 0, Math.PI*2);
    ctx.fillStyle=ballColor();
    ctx.fill();
    ctx.closePath();}

function draw(){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    drawBall();
    x += dx;
    y += dy;
    if(y+dy>canvas.height-ballRadius||y+dy<ballRadius){
        dy = -dy;
    }
    if(x+dx>canvas.width-ballRadius||x+dx<ballRadius){
        dx = -dx;}
    };

setInterval(draw,30);

If i run the function draw(), the ball will change color for every frame, making it very "flashing".

How do i get a fix color from getRandomColor() and store it in a variable (let say fixedColorOnly), so that the ball will only display fixedColorOnly until it hit another wall? By then the fixedColorOnly will store another color from getRandomNumber() and bounce and so on.

Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire