【发布时间】:2015-11-23 05:58:26
【问题描述】:
我在网上找到了这段代码,我正在努力弄明白。
window.onload = function(){
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
function drawStar(cx, cy, spikes, outerRadius, innerRadius){
var rot = Math.PI / 2 * 3;
var x = cx;
var y = cy;
var step = Math.PI / spikes;
ctx.strokeStyle = "#000";
ctx.beginPath();
ctx.moveTo(cx, cy - outerRadius) //100 - 30
for(i = 0; i < spikes; i++){
$(".display").append(Math.cos(rot) +" , ")
x = cx + Math.cos(rot) * outerRadius;
y = cy + Math.sin(rot) * outerRadius;
console.log("x : ", x, " y : ", y)
ctx.lineTo(x,y);
rot += step;
x = cx + Math.cos(rot) * innerRadius;
y = cy + Math.sin(rot) * innerRadius;
ctx.lineTo(x,y);
rot+= step;
}
ctx.lineTo(cx, cy- outerRadius);
ctx.closePath();
ctx.lineWidth = 1;
ctx.strokeStyle = "blue";
ctx.stroke()
ctx.beginPath();
ctx.arc(cx,cy,2, 0, (Math.PI * 2), true);
ctx.fillStyle = "red";
ctx.fill()
ctx.closePath();
}
drawStar(75, 100, 5,45, 15) //cx,cy,spikes, outerRadius, innerRadius
}
canvas{
background: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<canvas id="canvas" width="400" height="400"></canvas>
<div class="display"></div>
我看到上面写着var rot = Math.PI / 2 * 3 我想这是一个 270 度角,因为 90 * 3 = 270。我需要帮助弄清楚他们是如何得到星形右上角的点的。我相信是outerRadius。
他们x = cx + Math.cos(rot) * outerRadius; 是因为右上角(试图获得右上角)是 54 度的“腐烂”? .. 我认为(Math.PI / 5) * 180 / Math.PI 5 来自步进变量.. 等于 36 所以我做了 90 度 - 36 得到 54。我希望我能弄明白吗?我不确定他们为什么使用 270 度。你能详细说明一下吗?我不确定他们为什么使用var rot = Math.PI / 2 * 3,如果我稍微玩一下nums,我就会得到垃圾。我假设他们正在使用它来获得点构成的角度,但我很难将这些部分放在一起。
编辑:我把红点放在中心,以帮助我测量点到中心的角度。
【问题讨论】:
标签: javascript math canvas trigonometry