JavaScript Canvas - 是否可以根据Math.random进行绘制?

时间:2017-11-18 12:34:38

标签: javascript canvas

我正在为游戏创建一个非常基本的精灵(它是用Canvas / Context / LineTo绘制的)。我希望它的表达式基于两种不同的绘制方法随机改变。这是我的尝试:

            drawFace = function () {
                if (Math.random() < 0.05) {
                    Player.drawhappyface(context);
                }
                else if (Math.random() < 0.1) {
                    Player.drawsadface(context);
                }
            }

            drawFace();

我可以确认drawhappyface和drawadface draw方法独立于此函数(分别绘制微笑和皱眉)。但是使用这个功能及其逻辑,它们根本就不会被绘制(玩家完全没有脸)。那么,我写错了吗?我受到以下模拟的启发,该模拟使用Math.random不断动画表达式:http://www.blobsallad.se/

如果我改为编写这样的函数,那么画布上绝对没有绘制任何内容(所有其他精灵等也未绘制):

        drawFace = function (context) {
            if (Math.random() < 0.05) {
                Player.drawhappyface(context);
            }
            else if (Math.random() < 0.1) {
                Player.drawsadface(context);
            }
        }

        drawFace();

1 个答案:

答案 0 :(得分:1)

问题可能是您在Math.random()个语句中调用了if,然后它们会有不同的值。只需拨打Math.random()一次,并在每次需要时保存该值/致电drawFace尝试如下:

&#13;
&#13;
drawFace = function () {
    var randomNumber = Math.random();
    console.log(randomNumber);
    if (randomNumber < 0.05) {
        console.log('randomNumber < 0.05');
    }
    else if (randomNumber < 0.1) {
        console.log('randomNumber < 0.1');
    }
}

drawFace();
&#13;
&#13;
&#13;

如果你只想画出快乐或悲伤的面孔,你可以做得更简单if else

&#13;
&#13;
drawFace = function () {
    var randomNumber = Math.random();
    console.log(randomNumber);
    if (randomNumber < 0.5) {
        console.log('draw happy face');
    } else {
        console.log('draw sad face');
    }
}

drawFace();
&#13;
&#13;
&#13;

相关问题