我正在尝试使用JavaScript和<canvas>
元素对一个圆圈进行二等分。我使用了this question的接受答案中给出的公式来找到圆的边缘上的点,但出于某种原因,当我在圆上给出两个相对的点时(例如0和180,或90和270) )我没有得到一条穿过圆心的线条。
My code, which you can see on JSFiddle,制作了一个很好的Spirograph模式,这很酷,除了那不是我想要做的。
如何修复这条线以使线穿过中心?
(最终我试图绘制一个circle of fifths,但我现在要问的是如何让线条通过中心。一旦有效,我会继续其他步骤做五分之一圈,这显然会包括绘制更少的线并丢失Spirograph环面。)
答案 0 :(得分:4)
Javascript中的度数以弧度指定。不是检查大于或小于180,加上或减去180,而是使用Math.PI
弧度执行相同操作。
答案 1 :(得分:2)
Math
中的绘图函数和三角函数要求角度以弧度指定,而不是以度为单位。
差异:
function bisect(context, degrees, radius, cx, cy) {
// calculate the point on the edge of the circle
var x1 = cx + radius * Math.cos(degrees / 180 * Math.PI);
var y1 = cy + radius * Math.sin(degrees / 180 * Math.PI);
/* Trimmed */
// and calculate the point on the opposite side
var x2 = cx + radius * Math.cos(degrees2 / 180 * Math.PI);
var y2 = cy + radius * Math.sin(degrees2 / 180 * Math.PI);
/* Trimmed */
}
function draw(theCanvas) {
/* Trimmed */
// 2 * PI, which is 360 degree
context.arc(250, 250, 220, 0, Math.PI * 2, false);
/* Trimmed */
context.arc(250, 250, 110, 0, Math.PI * 2, false);
/* Trimmed */
// No need to go up to 360 degree, unless the increment does
// not divides 180
for (j = 2; j < 180; j = j + 3) {
bisect(context, j, 220, 250, 250);
}
/* Trimmed */
}
这是来自JSFiddle的完整源代码,请保留完整副本以防万一。
<强> HTML 强>
<canvas id="the_canvas" width="500" height="500"></canvas>
<强> CSS 强>
canvas {
border:1px solid black;
}
<强>的JavaScript 强>
function bisect(context, degrees, radius, cx, cy) {
// calculate the point on the edge of the circle
var x1 = cx + radius * Math.cos(degrees / 180 * Math.PI);
var y1 = cy + radius * Math.sin(degrees / 180 * Math.PI);
// get the point on the opposite side of the circle
// e.g. if 90, get 270, and vice versa
// (super verbose but easily readable)
if (degrees > 180) {
var degrees2 = degrees - 180;
} else {
var degrees2 = degrees + 180;
}
// and calculate the point on the opposite side
var x2 = cx + radius * Math.cos(degrees2 / 180 * Math.PI);
var y2 = cy + radius * Math.sin(degrees2 / 180 * Math.PI);
// now actually draw the line
context.beginPath();
context.moveTo(x1, y1)
context.lineTo(x2, y2)
context.stroke();
}
function draw(theCanvas) {
var context = theCanvas.getContext('2d');
// draw the big outer circle
context.beginPath();
context.strokeStyle = "#222222";
context.lineWidth = 2;
context.arc(250, 250, 220, 0, Math.PI * 2, false);
context.stroke();
context.closePath();
// smaller inner circle
context.beginPath();
context.strokeStyle = "#222222";
context.lineWidth = 1;
context.arc(250, 250, 110, 0, Math.PI * 2, false);
context.stroke();
context.closePath();
for (j=2; j < 180; j = j + 3) {
bisect(context, j, 220, 250, 250);
}
}
$(function () {
var theCanvas = document.getElementById('the_canvas');
console.log(theCanvas);
draw(theCanvas, 50, 0, 270);
});