是否可以在不使用.arc()或任何其他HTML标签的情况下绕圆?

时间:2019-04-26 09:05:32

标签: javascript html5 canvas

我正在尝试使用HTML中的画布进行实验,当我使用.arc()圈出一个圆时,我不知道如何获得所有要点。有人知道吗?

3 个答案:

答案 0 :(得分:0)

在html中使用svg,例如:

圆形图像:

<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <circle cx="50" cy="50" r="50"/>
</svg>

您还可以更改半径和其他详细信息。 查看此链接:https://www.w3schools.com/graphics/svg_intro.asp

答案 1 :(得分:0)

您可以绘制一个圆并得到要点,您可以执行以下操作:

let c = document.getElementById("circle");
let ctx = c.getContext("2d");
let cw = c.width = 250;
let ch = c.height = 200;
let cx = cw / 2,
  cy = ch / 2;
  //the array of points
  let points = []


ctx.lineWidth = 3;
ctx.strokeStyle = "#64b150";

//circle's radius
let r = 75;

ctx.beginPath();
for (let a = 0; a < 2*Math.PI; a+=.1) {
  let o = {}//a point on the circle
  o.x = cx + r * Math.cos(a);
  o.y = cy + r * Math.sin(a);
  points.push(o);
  ctx.lineTo(o.x, o.y)
  }
ctx.closePath();
ctx.stroke();
canvas{border:1px solid;}
<canvas id="circle"></canvas>

在Kaiido发表评论时,您需要选择其他增量而不是.1:for (let a = 0; a < 2*Math.PI; a+= increment) {

答案 2 :(得分:0)

要渲染近似的圆并获取该圆的点,可以在圆形图案线中绘制一系列线段,如下所示:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

/* Center and radius of circle */
const centerX = 50;
const centerY = 50;
const radius = 25;

/* Array containing your points */
const points = [];

/* Configure line rendering and start drawing a path */
ctx.lineWidth = 2;
ctx.strokeStyle = "red";
ctx.beginPath();

/* Iterate each side and calculate the position of it's starting point */
for (let i = 0, sides = 50; i < sides; i ++) {
  
  const angle = (i / sides) * 2 * Math.PI;
  const x = centerX + radius * Math.cos(angle);
  const y = centerY + radius * Math.sin(angle);
  
  points.push({ x, y });
  ctx.lineTo(x, y);
  }
  
/* Complete path and render as stroke */
ctx.closePath();
ctx.stroke();

console.log(points);
<canvas id="canvas" width="200" height="200"></canvas>