tim*_*l0l -3 javascript html5-canvas
我想获得一些如何用HTML5 canvas + Javascript绘制齿轮形状的技巧.
不导入图片,但实际上是自己制作图片.
我认为这将是某种循环,取决于你想要齿轮有多少牙齿等.
但我不知道trigonemetri的数学等.
小智 8
齿轮/齿轮的渲染并不复杂 - 初始化内半径和外半径的一些基本值,锥度值和角度步长.
示例值:
var cx = 200, // center x
cy = 200, // center y
notches = 7, // num. of notches
radiusO = 180, // outer radius
radiusI = 130, // inner radius
taperO = 50, // outer taper %
taperI = 35, // inner taper %
// pre-calculate values for loop
pi2 = 2 * Math.PI, // cache 2xPI (360deg)
angle = pi2 / (notches * 2), // angle between notches
taperAI = angle * taperI * 0.005, // inner taper offset (100% = half notch)
taperAO = angle * taperO * 0.005, // outer taper offset
a = angle, // iterator (angle)
toggle = false; // notch radius level (i/o)
Run Code Online (Sandbox Code Playgroud)
设置画布并使用单个循环来迭代基于这些值的圆和一个切换开关,它将绘制内部和内部到外部线的外部所有其他级别:
// move to starting point
ctx.moveTo(cx + radiusO * Math.cos(taperAO), cy + radiusO * Math.sin(taperAO));
// loop
for (; a <= pi2; a += angle) {
// draw inner to outer line
if (toggle) {
ctx.lineTo(cx + radiusI * Math.cos(a - taperAI),
cy + radiusI * Math.sin(a - taperAI));
ctx.lineTo(cx + radiusO * Math.cos(a + taperAO),
cy + radiusO * Math.sin(a + taperAO));
}
// draw outer to inner line
else {
ctx.lineTo(cx + radiusO * Math.cos(a - taperAO), // outer line
cy + radiusO * Math.sin(a - taperAO));
ctx.lineTo(cx + radiusI * Math.cos(a + taperAI), // inner line
cy + radiusI * Math.sin(a + taperAI));
}
// switch level
toggle = !toggle;
}
// close the final line
ctx.closePath();
Run Code Online (Sandbox Code Playgroud)
创建中心孔的一种方法是使用合成:
// "erase" mode (term simplified)
ctx.globalCompositeOperation = 'destination-out';
// create circle (full arc)
ctx.beginPath();
ctx.moveTo(cx + radiusH, cy);
ctx.arc(cx, cy, radiusH, 0, pi2);
ctx.closePath();
// creates the hole
ctx.fill();
// reset comp. mode
ctx.globalCompositeOperation = 'source-over';
Run Code Online (Sandbox Code Playgroud)
另一种方法是通过在填充和描边之前添加整体的弧形路径来使用填充规则偶数 - 奇数.请注意,您需要使用它moveTo()
来分解描边路径:
// without filling/stroking, continue with:
// Punch hole
ctx.moveTo(cx + radiusH, cy);
ctx.arc(cx, cy, radiusH, 0, pi2);
// now fill using even-odd rule
ctx.fillStyle = '#aaa';
ctx.fill("evenodd");
// stroke
ctx.lineWidth = 2;
ctx.strokeStyle = '#000';
ctx.stroke();
Run Code Online (Sandbox Code Playgroud)