2013-01-24 58 views

回答

3

下面是一些JavaScript代码,我创建的回答我的问题:

function drawCylinder (x, y, w, h) { 
    context.beginPath(); //to draw the top circle 
    for (var i = 0 * Math.PI; i < 2 * Math.PI; i += 0.001) { 

    xPos = (this.x + this.w/2) - (this.w/2 * Math.sin(i)) * 
     Math.sin(0 * Math.PI) + (this.w/2 * Math.cos(i)) * 
     Math.cos(0 * Math.PI); 

    yPos = (this.y + this.h/8) + (this.h/8 * Math.cos(i)) * 
     Math.sin(0 * Math.PI) + (this.h/8 * 
     Math.sin(i)) * Math.cos(0 * Math.PI); 

    if (i == 0) { 
     context.moveTo(xPos, yPos); 

    } 
    else 
    { 
     context.lineTo(xPos, yPos); 
    } 
    } 
    context.moveTo(this.x, this.y + this.h/8); 
    context.lineTo(this.x, this.y + this.h - this.h/8); 

    for (var i = 0 * Math.PI; i < Math.PI; i += 0.001) { 
    xPos = (this.x + this.w/2) - (this.w/2 * Math.sin(i)) * Math.sin(0 * Math.PI) + (this.w/2 * Math.cos(i)) * Math.cos(0 * Math.PI); 
    yPos = (this.y + this.h - this.h/8) + (this.h/8 * Math.cos(i)) * Math.sin(0 * Math.PI) + (this.h/8 * Math.sin(i)) * Math.cos(0 * Math.PI); 

    if (i == 0) { 
     context.moveTo(xPos, yPos); 

    } 
    else 
    { 
     context.lineTo(xPos, yPos); 
    } 
    } 
    context.moveTo(this.x + this.w, this.y + this.h/8); 
    context.lineTo(this.x + this.w, this.y + this.h - this.h/8);    
    context.stroke(); 
} 
+0

你怎么称呼这个功能? –

0

如果你想画一个3D柱体,最简单的方法是使用像TQuery的库(http://jeromeetienne.github.com/tquery/):如果你想画一个“2D”缸

var world = tQuery.createWorld().boilerplate().start(); 
var object = tQuery. createCylinder().addTo(world); 

,你可以这样做使用canvas 2d API绘制一个矩形,然后在其上方绘制一个椭圆。它将显示为一个圆柱体。

+0

我试过后面的建议。但问题是将椭圆放在它和控制盒上。 :-( – Kandy7

1

谢谢!这正是我正在寻找的。在我自己的代码中实现你的函数时,我做了一些改变,例如传递canvas上下文作为参数,简化了数学运算并让代码通过了JSLint。

function drawCylinder(ctx, x, y, w, h) { 
    'use strict'; 
    var i, xPos, yPos, pi = Math.PI, twoPi = 2 * pi; 

    ctx.beginPath(); 

    for (i = 0; i < twoPi; i += 0.001) { 
     xPos = (x + w/2) - (w/2 * Math.cos(i)); 
     yPos = (y + h/8) + (h/8 * Math.sin(i)); 

     if (i === 0) { 
      ctx.moveTo(xPos, yPos); 
     } else { 
      ctx.lineTo(xPos, yPos); 
     } 
    } 
    ctx.moveTo(x, y + h/8); 
    ctx.lineTo(x, y + h - h/8); 

    for (i = 0; i < pi; i += 0.001) { 
     xPos = (x + w/2) - (w/2 * Math.cos(i)); 
     yPos = (y + h - h/8) + (h/8 * Math.sin(i)); 

     if (i === 0) { 
      ctx.moveTo(xPos, yPos); 
     } else { 
      ctx.lineTo(xPos, yPos); 
     } 
    } 
    ctx.moveTo(x + w, y + h/8); 
    ctx.lineTo(x + w, y + h - h/8); 

    ctx.stroke(); 
}