制作一个随机艺术生成器的作业。我们需要让正方形随机弹出,但我不知道如何画正方形。目前我的代码是这样的:
function drawSquare(canvas, context, color){
var x= Math.floor(Math.random()*canvas.width);
var y= Math.floor(Math.random()*canvas.height);
context.beginPath();
context.fillStyle = color;
context.fillRect (x,y, canvas.width, canvas.height)
}
window.innerWidth*0.1
- 这将转换为一定数量的像素(取决于屏幕宽度)。是的,调用Math.random()
来生成一个介于> 0和<= 1之间的新随机数。顺便说一下,您不需要使用Math.floor
。 - GeorgeMath.random()
将计算出一个数字,因此您可以想象它只是一个数字(介于0和1之间)。所以在您的if 语句if (Math.random() < 0.4) { ... } else { ... }
的情况下,它将计算出像这样的一些数字:if (0.54462 < 0.4 ) { ...
然后被计算为true
或false
。使用该代码,它将大约40%的时间计算为true。 - George