简体   繁体   English

是否可以使用 Javascript 在画布中的椭圆的周长上等距地绘制化身?

[英]Is it possible to draw avatars equally spaced out on the perimeter of an ellipse in canvas with Javascript?

我在画布上绘制椭圆没有问题,但是如何在椭圆的周长上等距绘制项目(在我的情况下最多 8 个玩家头像)?

The key is to divide 360° by the number of players, then calculate the angle for each avatar and use cosine and sine to determine the position:关键是将360°除以玩家人数,然后计算每个头像的角度,并使用余弦和正弦来确定位置:

 const w = can.width = window.innerWidth; const h = can.height = window.innerHeight; const con = can.getContext("2d"); const tau = Math.PI * 2; // center ellipse inside canvas const cx = w / 2, cy = h / 2; const rx = w / 2.5, ry = rx * 0.3; con.beginPath(); con.ellipse(cx, cy, rx, ry, 0, 0, tau); con.closePath(); con.stroke(); // example: 7 avatars const total = 7; for (var i = 0; i < total; i++) { // calculate partial angle for each avatar var angle = i * tau / total; con.beginPath(); // calculate position con.ellipse(cx + Math.cos(angle) * rx, cy + Math.sin(angle) * ry, 10, 10, 0, 0, tau); con.closePath(); con.stroke(); }
 body { margin: 0; } #can { display: block; height: 100vh; }
 <canvas id="can"></canvas>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM