简体   繁体   中英

Canvas - How to draw hexagon, but vertex up and without rotate

I need to draw hexagon but vertex has to go up. I created this using rotate method from canvas, but now I have to make it without rotating. I need hexagon path to be like this:

在此处输入图像描述

This is how my hexagon path look like now:

在此处输入图像描述

 let size = 21 let x = 70 let y = 60 let side = 0 path = new Path2D(); path.moveTo(x + size * Math.cos(0), y + size * Math.sin(0)); for (side; side < 7; side++) { path.lineTo(x + size * Math.cos(side * 2 * Math.PI / 6), y + size * Math.sin(side * 2 * Math.PI / 6)); }

Is there any way to make a path for this hexagon to be placed with vertex to up without using rotate method?

This method not only gets you pentagons but will also draw you any polygon.


function polygon(x, y, N, r, color) { //x&y are positions, N is side number, r is size, color is to fill

ctx.beginPath();
  ctx.moveTo (x + r * Math.cos(0), y + r *  Math.sin(0));

  for (var i = 1; i <= N; i += 1) {
    ctx.lineTo (x + r * Math.cos(i * 2 * Math.PI / N), y + r * Math.sin(i * 2 * Math.PI / N));
}
//Below draws the shape
ctx.strokeStyle = color;
ctx.lineWidth = 1;
ctx.stroke();
ctx.save();
//Below fills the shape
ctx.fillStyle = color;
ctx.fill();
ctx.restore();
}

You can take out the fill() part if you just want the outline, but if you strictly need a pentagon, just replace all instances of N with 5.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM