Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a cylinder on html5 canvas

I want to draw a cylinder on canvas with control box to re size the cylinder.

like image 642
Kandy7 Avatar asked Dec 09 '25 20:12

Kandy7


1 Answers

Here's some javascript code I created to answer my own question:

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();
}
like image 151
Kandy7 Avatar answered Dec 12 '25 10:12

Kandy7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!