我有一个canvas
,我用它来画球。但是我想从1填充球,在画布内随机空间说10个球。我应该使用10个单独的函数({{1} },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;
}

答案 0 :(得分:2)
你可以只调用一个函数十次,而不是创建十个函数来做同样的事情,或者你可以在其中引入一个循环,循环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>
答案 1 :(得分:0)
您可以创建描述球的对象,并具有可以绘制的功能或其他行为
var ctx = canvas.getContext("2d");
function createBall(x,y,radius,color){
return { // return a new ball
x,y,radius,color, // set the balls properties
draw(ctx){ // add a draw function
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fill();
return this; // to allow chaining
},
}
}
const colors = "#C30A4C,#CCAB7C,#CC984B,#DE880C,#546D84,#7F858A,#697785,#375E85,#125290,#94B870";
const ballRadius = 20;
const rand = (size)=>{return Math.floor(Math.random() * size)}; // rand util
const balls = []; // an array to hold the balls
balls.push( // add some balls to the ball array
...colors
.split(",")
.map(color=>createBall(
rand(ctx.canvas.width),
rand(ctx.canvas.height),
ballRadius,
color
))
)
balls.forEach(ball=>ball.draw(ctx)); // draw them.
<canvas id="canvas" width=512 height=200></canvas>