Reputation: 2953
I am trying to draw a quadrilateral on my canvas with the p5.js library. I am do this by creating a custom vertex shape. See the code below.
var tr;
function setup(){
createCanvas(window.innerWidth, window.innerHeight);
tr = new surface_triangle(width/2, height/2, 100, 90, "a", 12334);
}
function draw(){
background(0);
tr.draw_triangle();
}
class surface_triangle{
constructor(x, y, size, rotation, properties, id){
this.size = size;
this.h = size * (Math.sqrt(3)/2);
this.x = x;
this.y = y;
}
draw_triangle(){
beginShape();
fill(255,0,0);
vertex(this.x, this.y - this.h/2);
vertex(this.x - this.size/2, this.y + this.h/2);
vertex(this.x + this.size/2, this.y + this.h/2);
endShape(CLOSE)
fill(255);
ellipse(this.x, this.y, 10, 10);
}
}
As you see i managed to draw the triangle but the center point is not correct. And i have no idea why my center point is off? See image below:
@kevingworkman was totally right in his answer but i am trying to draw the triangle from the center point. So i will have a centerx and a centery and now i need to calculate the 3 points of the triangle relative to this center point. Like this image ->.
How would i go about doing this? Since my previous code clearly draws from a different point.
All tips and suggestions are greatly appreciated!
Upvotes: 2
Views: 832
Reputation: 42174
It's an optical illusion. The square is in the "center" of the top and bottom of the triangle. Zoom into your image and count the pixels above and below the edges of the circle. You'll find that there are 75 pixels above the circle, and 75 pixels below (give or take a couple because of anti-aliasing).
You can also see this by drawing a square with the same top and bottom as the triangle.
This looks weird to our human eyes because we want the center to be in between all three of the points, not just the top and bottom.
You can fix this by taking the average of all three points to find the center of the triangle.
Edit: If you want the provided center to be the real center of all three points, then you have to change how you calculate the three points. You can use basic trig (the cos()
and sin()
functions) for that.
Upvotes: 1