Gha*_*ito 1 javascript oop canvas function object
我已经声明了下一个正方形,这很简单,但是现在我想对一个圆做同样的事情...
我该怎么办?谢谢。
//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);
Run Code Online (Sandbox Code Playgroud)
您可以像处理一样进行此操作Square
。唯一真正的区别是使用该arc(x, y, r, startAngle, endAngle)
方法。使用它绘制一个圆,您将startAngle
和定义endAngle
为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.
Run Code Online (Sandbox Code Playgroud)
因此,使用与您上面使用的相同的编码样式,这就是制作的方法Circle
。如您所见,它几乎以相同的方式完成。这是下面的代码段:
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.
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
canvas{ border: 1px solid black; }
Run Code Online (Sandbox Code Playgroud)