【问题标题】:How to align different sizes of circles to middle?如何将不同大小的圆圈对齐到中间?
【发布时间】:2017-08-04 09:41:04
【问题描述】:

我想将不同大小的圆对齐到一条中间线,例如:

1 圈:

var c=document.getElementById("myCanvas");
var ctx=document.getElementById("myCanvas").getContext("2d");
var r1=Math.random()*50;

ctx.beginPath();
ctx.fillStyle="#"+((1<<24)*Math.random()|0).toString(16);
ctx.arc(c.width/2,c.height/2,r1,0,2*Math.PI);
ctx.fill();
<div>
    <canvas id="myCanvas" width="500" height="100" style="position:absolute;border:1px solid black;"></canvas>
    <div style="position:absolute;width:250px;height:100px;border:1px solid black;"/>
</div>

2个圈子:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

var r1=Math.random()*50;
var r2=Math.random()*50;

ctx.beginPath();
ctx.fillStyle="#"+((1<<24)*Math.random()|0).toString(16);
ctx.arc(-r2+c.width/2,c.height/2,r1,0,2*Math.PI);
ctx.fill();

ctx.beginPath();
ctx.fillStyle="#"+((1<<24)*Math.random()|0).toString(16);
ctx.arc(r1+c.width/2,c.height/2,r2,0,2*Math.PI);
ctx.fill();
<div>
    <canvas id="myCanvas" width="500" height="100" style="position:absolute;border:1px solid black;"></canvas>
    <div style="position:absolute;width:250px;height:100px;border:1px solid black;"/>
</div>

3,4,...n 圈怎么样?

var r[]=[Math.random()*50,Math.random()*50,...];
for(var i=0;i<r.length;i++){
    ctx.beginPath();
    ctx.fillStyle="#"+((1<<24)*Math.random()|0).toString(16);
    ctx.arc(???+c.width/2,c.height/2,r[i],0,2*Math.PI);
    ctx.fill();
}

它的一般公式是什么?

【问题讨论】:

    标签: javascript html algorithm math canvas


    【解决方案1】:

    您首先需要通过对所有半径求和来计算totalRadius。最左边的点是cavnas.width/2 - totalRadius。然后,您只需使用前一个左侧绘制每个下一个圆圈

    const canvas = document.querySelector('#myCanvas')
    const ctx = canvas.getContext("2d")
      
    const draw = (r, center) => {
      ctx.beginPath()
      ctx.fillStyle="#"+((1<<24)*Math.random()|0).toString(16);
      ctx.arc(center, canvas.height/2, r, 0, 2*Math.PI);
      ctx.fill();
    }
    
    const randomR = () => 10 + Math.random()*40
    
    const rs = new Array(7).fill().map(randomR)
    
    // calculate the very left point
    let left = canvas.width/2 - rs.reduce((sum, r) => sum + r)
    
    rs.forEach(r => {
      // center will be current left + r
      draw(r, left + r)
      
      // next left moved by diameter
      left += 2*r
    })
    <div>
            <canvas id="myCanvas" width="500" height="100" style="position:absolute;border:1px solid black;"></canvas>
            <div style="position:absolute;width:250px;height:100px;border:1px solid black;"/>
        </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 2019-10-30
      • 2014-07-08
      • 1970-01-01
      • 2019-04-09
      • 1970-01-01
      相关资源
      最近更新 更多