2017-02-22 26 views
0

我有一個canvas,我用它來畫球。但是我想從1填充球以在畫布內的隨機空間中說10個球。我應該使用10個單獨的函數( drawBall1()drawBall2,...,drawBall10)?在畫布中填充更多類型的相似對象

OR

是否有任何其他的方法呢?

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>

回答

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>

2

你只需調用一個函數,而不是創建十大功能它做同樣的事情,或者你可能會引入一個循環中,其循環10次給你,depedning什麼適合的十倍你更好。

我希望我能正確理解你的問題。

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>

+0

是它的工作原理,但它只是一種變通方法對象與for循環.. –

+0

也許,我剛剛得到你的問題錯了。解決方法是什麼意思?如果你想重複一次N次,那麼循環就是爲了它。 它可能是某種循環或輸入相同代碼的十倍。 –

+0

是的,你是正確的你的方式,但那件事我知道了,但謝謝:) –