我正在尝试绘制一个Cylinder,我已经使用HTML5 canvas& amp; javascript之前,但我现在没有很多时间,这可能是我正在寻找的开销。
如果您发现错误,请告诉我。感谢。
这是我的jsfiddle:http://jsfiddle.net/pa9reay9/
代码:
使用Javascript:
var c = document.getElementById("myCanvas");
var context = c.getContext("2d");
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();
}
drawCylinder(10,10,100,50);
HTML:
<p>Where is my canvas?</p>
<div>
<canvas id="myCanvas" width="200" height="200"></canvas>
</div>
CSS:
div {
border: 2px solid black;
}
p {
font-family: calibri;
font-size: 36px;
text-decoration: underline;
color: red;
padding: 0;
margin-left: 5px;
}
答案 0 :(得分:1)
x,y,w,h
是方法的参数,而不是对象属性,所以只需删除所有this.
:
var c = document.getElementById("myCanvas");
var context = c.getContext("2d");
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 = (x + w / 2) - (w / 2 * Math.sin(i)) *
Math.sin(0 * Math.PI) + (w / 2 * Math.cos(i)) *
Math.cos(0 * Math.PI);
yPos = (y + h / 8) + (h / 8 * Math.cos(i)) *
Math.sin(0 * Math.PI) + (h / 8 *
Math.sin(i)) * Math.cos(0 * Math.PI);
if (i == 0) {
context.moveTo(xPos, yPos);
}
else
{
context.lineTo(xPos, yPos);
}
}
context.moveTo(x, y + h / 8);
context.lineTo(x, y + h - h / 8);
for (var i = 0 * Math.PI; i < Math.PI; i += 0.001) {
xPos = (x + w / 2) - (w / 2 * Math.sin(i)) * Math.sin(0 * Math.PI) + (w / 2 * Math.cos(i)) * Math.cos(0 * Math.PI);
yPos = (y + h - h / 8) + (h / 8 * Math.cos(i)) * Math.sin(0 * Math.PI) + (h / 8 * Math.sin(i)) * Math.cos(0 * Math.PI);
if (i == 0) {
context.moveTo(xPos, yPos);
}
else
{
context.lineTo(xPos, yPos);
}
}
context.moveTo(x + w, y + h / 8);
context.lineTo(x + w, y + h - h / 8);
context.stroke();
}
drawCylinder(10,10,100,50);