【问题标题】:How to change the ball color every time it bounces off the wall?每次从墙上反弹时如何改变球的颜色?
【发布时间】:2015-06-06 02:22:56
【问题描述】:

我刚刚在搜索一些 JavaScript 代码时看到了这个问题ball bounce。它的代码很简单,但是如果我们想在每次球从墙上反弹时随机改变球的颜色该怎么办。

我的想法:

有一个随机颜色生成器并使用它。像这样的

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;
}

但是如何改变球的颜色。我试过context.fill() 但没有帮助

【问题讨论】:

    标签: javascript html css html5-canvas


    【解决方案1】:

    应该像球撞墙时调用函数一样直接,像这样

    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

    【讨论】:

    • 谢谢。就在你发布这个之前,我让它运行起来。找到 context.fillStyle 属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    相关资源
    最近更新 更多