gpt4 book ai didi

javascript - 在 Canvas 中绘制一个球作为对象

转载 作者:行者123 更新时间:2023-11-30 08:40:55 24 4
gpt4 key购买 nike

我已经声明了下一个正方形,这很简单,但现在我想对一个圆做同样的事情......

我该怎么做?谢谢。

//Create Var
var squa = new Square(320, 380, 50, 50);

//Define the square
function Square(x, y, width, height) {
"use strict";
this.x = (x === null) ? 0 : x;
this.y = (y === null) ? 0 : y;
this.width = (width === null) ? 0 : width;
this.height = (height === null) ? this.width : height;
}

//Draw the square as object
squa.fill(ctx);

最佳答案

您可以像处理 Square 一样处理这个问题。唯一真正的区别是使用 arc(x, y, r, startAngle, endAngle) 方法。用它画一个圆,你定义 startAngleendAngle 为 0 和 2pi。像这样:arc(x, y, r, 0, Math.PI*2)。要绘制圆圈,您首先需要调用 ctx.beginPath(); 来声明您要绘制一些路径或圆弧。例如,在 (100,100) 处绘制一个半径为 10 的圆:

ctx.beginPath();
ctx.arc(100, 100, 10, 0, Math.PI*2);
ctx.fill(); // fill() is to fill in the circle, stroke() is for a empty circle.

因此,使用您在上面使用的相同编码风格,这里是您如何制作一个Circle。如您所见,它的完成方式几乎相同。下面是一个片段:

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

//Create Var
var circ = new Circle(100, 100, 20);

//Define the circle
function Circle(x, y, r) {
"use strict";
this.x = (x === null) ? 0 : x;
this.y = (y === null) ? 0 : y;
this.r = (r === null) ? 0 : r;

this.fill = function(ctx) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI*2);
ctx.fill();
}
}

//Draw the circle as object
circ.fill(ctx);
canvas{ border: 1px solid black; }
<canvas width=200 height=200 id="canvas"></canvas>

关于javascript - 在 Canvas 中绘制一个球作为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26412567/

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