简体   繁体   English

每次反弹时如何改变球的颜色?

[英]How to change the ball color every time it bounces off the wall?

I just saw this question ball bounce while searching for some JavaScript code. 我只是在搜索一些JavaScript代码时看到这个问题球反弹 Its easy code but what to do if we want to change the color randomly of the ball every time it bounces off the wall. 它的代码很简单,但是如果我们想在球每次弹回墙壁时随机改变其颜色,该怎么办。

My thoughts: 我的想法:

Have a random color generator and use it. 有一个随机的颜色生成器并使用它。 Something like this 像这样

function get_random_color() {
    var letters = 'ABCDE'.split('');
    var color = '#';
    for (var i=0; i<3; i++ ) {
        color += letters[Math.floor(Math.random() * letters.length)];
    }
    return color;
}

But how to change the color of the ball. 但是如何改变球的颜色。 I tried context.fill() but no help 我尝试了context.fill()但没有帮助

Should be as straight forward as calling the function when the ball hits a wall, like this 这样当球碰到墙时应该像调用函数一样简单

function myFunction() {
    var context;
    var dx = 4;
    var dy = 4;
    var y = 150;
    var x = 10;
    var color = get_random_color();

    function draw() {
        context = myCanvas.getContext('2d');
        context.clearRect(0, 0, 400, 400);
        context.beginPath();
        context.fillStyle = color;
        context.arc(x, y, 10, 0, Math.PI * 2, true);
        context.closePath();
        context.fill();
        if (x < 0 || x > 400) {
            dx = -dx;
            color = get_random_color();
        }
        if (y < 0 || y > 300) {
            dy = -dy;
            color = get_random_color();
        }
        x += dx;
        y += dy;
    }
    setInterval(draw, 10);
}

FIDDLE 小提琴

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

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