gpt4 book ai didi

javascript - 需要帮助在 Canvas 上的矩形内绘制多个球

转载 作者:行者123 更新时间:2023-12-01 00:30:33 25 4
gpt4 key购买 nike

我需要在一个矩形内绘制多个球。我有一个矩形和 4 个信息。矩形的宽度和高度。每行的球数和行数。比如说,我必须在同一条线上画 4 个球。从 Angular 落开始(我能够做到),但我不知道如何绘制超过 2 个球,例如:如果我有 3 个球,我需要在 Angular 落绘制 2 个,在中间绘制 1 个,如果我有 4 个球... 2 个在 Angular 落,2 个在中间。我有将矩形视为矩阵的想法,但没有运气.. link to see what I mean

最佳答案

如果您需要在线绘制 n 个龙珠,那么您可以将长度除以 n + 1 以获得球中心之间的间距,或者如果您希望开始和结束时有不同的偏移量,那么您可以除以 (宽度 - 2 *偏移)/(n - 1)。

<canvas id="canvas" width="300" height="100">
</canvas>

<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

class Rect {
constructor(x, y, width, heght) {
this.x = x;
this.y = y;
this.width = width;
this.heght = heght;
}
}

class Circle {
constructor(x, y, radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
}

class Scene
{
constructor() {
this.items = [];
}
clear() {
this.items = [];
}
add(item) {
this.items.push(item);
}
draw(ctx) {
for(let item of this.items) {
if (item instanceof Rect) {
ctx.beginPath();
ctx.rect(item.x, item.y, item.width, item.heght);
ctx.stroke();
} else if (item instanceof Circle) {
ctx.beginPath();
ctx.arc(item.x, item.y, item.radius, 0, 2 * Math.PI);
ctx.stroke();
}
}
}
}

const scene = new Scene();
scene.clear();
scene.add(new Rect(0, 0, 300, 100));

let n = 5;
let offset = 30;
let spacing = ((300 - 2 * offset ) / (n - 1));

for (let i = 0; i < n; i++) {
scene.add(new Circle(i * spacing + offset, 50, 25))
}
scene.draw(ctx);

</script>

关于javascript - 需要帮助在 Canvas 上的矩形内绘制多个球,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58582535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com