我正在使用以下内容在html画布上绘制多边形:
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
var numberOfSides = 6,
size = 20,
Xcenter = 25,
Ycenter = 25;
ctx.beginPath();
ctx.moveTo (Xcenter + size * Math.cos(0), Ycenter + size * Math.sin(0));
for (var i = 1; i <= numberOfSides;i += 1) {
ctx.lineTo (Xcenter + size * Math.cos(i * 2 * Math.PI / numberOfSides), Ycenter + size * Math.sin(i * 2 * Math.PI / numberOfSides));
}
ctx.strokeStyle = "#000000";
ctx.lineWidth = 10;
ctx.stroke();
不幸的是,它在多边形的末尾留下了一个间隙。知道如何解决这个问题吗?
答案 0 :(得分:3)
而不是绘制到所有6个点,只绘制到前5个,然后调用ctx.closePath();
http://jsfiddle.net/757mavjb/2/
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
var numberOfSides = 6,
size = 20,
Xcenter = 25,
Ycenter = 25;
ctx.beginPath();
ctx.moveTo (Xcenter + size * Math.cos(0), Ycenter + size * Math.sin(0));
for (var i = 1; i < numberOfSides;i += 1) {
ctx.lineTo (Xcenter + size * Math.cos(i * 2 * Math.PI / numberOfSides), Ycenter + size * Math.sin(i * 2 * Math.PI / numberOfSides));
}
ctx.closePath();
ctx.strokeStyle = "#000000";
ctx.lineWidth = 10;
ctx.stroke();
(请注意从i <= numberOfSides
到i < numberOfSides
的更改)
答案 1 :(得分:1)
尝试再画一面以填补空白:
for (var i = 1; i <= numberOfSides+1;i += 1) {
ctx.lineTo (Xcenter + size * Math.cos(i * 2 * Math.PI / numberOfSides), Ycenter + size * Math.sin(i * 2 * Math.PI / numberOfSides));
}