我有一个 Canvas
,我用它来绘制球。但是我想在 Canvas 内的随机空间中填充从1到10个球的球。我应该使用10个单独的函数(drawBall1()
,drawBall2
,....,drawBall10
)?
或
还有其他方法吗?
var canvas = document.getElementById("myCanvas");
var ballRadius = 10;
var ctx = canvas.getContext("2d");
function draw() {
drawBall();
}
function drawBall() {
ctx.beginPath();
ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = "green";
ctx.fill();
}
draw();
canvas {
background: #eee;
display: block;
margin: 0 auto;
}
<canvas id="myCanvas"></canvas>
最佳答案
您可以只调用一个函数十次,而不是创建十个执行相同操作的函数,或者您可以引入一个循环,在其中为您循环 10 次,具体取决于什么更适合您。
我希望我正确理解了你的问题。
function drawBall(x, y, radius, color, ctx)
{
ctx.beginPath()
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fillStyle = color;
ctx.fill();
}
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
var x, y, color,
colors = ['#ffc0cb', '#008080', '#b0e0e6', '#003366', '#666666', '#faebd7'],
radius = 10,
ballCount = 10;
for (var i = 0; i < ballCount; i++)
{
x = Math.floor(Math.random() * (canvas.width + 1));
y = Math.floor(Math.random() * (canvas.height + 1));
color = colors[Math.floor(Math.random() * colors.length)];
drawBall(x, y, radius, color, ctx);
}
<canvas width="200px" height="200px" id="canvas" style="border: 1px solid black"></canvas>
关于javascript - 在 Canvas 中填充更多类型的相似对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42401600/