使用圆弧在 javascript 中创建一个圆

Using arc to create a circle in javascript

我正在动态创建一个 canvas,然后画一个圆。 然而,如图所示,圆出现拉伸和偏移:

var max = 50;
var canvas = document.createElement('canvas');
canvas.id = "mazecanvas";
var size = (document.documentElement.clientWidth / 100) * max;
canvas.style.width = size + "px";
canvas.style.height = size + "px";
canvas.style.position = "absolute";
canvas.style.left = size / 2 + "px";
canvas.style.top = (document.documentElement.clientHeight / 2) - (size / 2) + "px";
document.body.appendChild(canvas);
var x, y;
var ctx = canvas.getContext('2d');

function circle() {
  ctx.globalCompositeOperation = "destination-in";
  ctx.beginPath();
  console.log(x, y);
  ctx.arc(x, y, 10, 0, 2 * Math.PI, false);
  ctx.closePath();
  ctx.fill();
}

function getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect();
  return {
    x: evt.clientX - rect.left,
    y: evt.clientY - rect.top
  };
}
canvas.addEventListener('mousemove', function(evt) {
  var mousePos = getMousePos(canvas, evt);
  x = mousePos.x;
  y = mousePos.y;
}, false);

function draw() {
  ctx.globalCompositeOperation = "source-over";
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  for (var i = 0; i < max; i++) {
    for (var j = 0; j < max; j++) {
      ctx.fillStyle = 'rgb(' + Math.floor(255 - 5.5 * i) + ',' + Math.floor(255 - 5.5 * j) + ',0)';
      ctx.fillRect(j * (canvas.width / max), i * (canvas.height / max), canvas.width / max, canvas.height / max);
    }
  }
  circle();
  setTimeout(draw, 10);
}
draw();

我不明白我做错了什么,我知道这是与 canvas 创建有关,因为当我删除它并用静态替换它时,问题就消失了:

var max = 50;
var canvas = document.getElementById('canvas');
var x, y;
var ctx = canvas.getContext('2d');

function circle() {
  ctx.globalCompositeOperation = "destination-in";
  ctx.beginPath();
  console.log(x, y);
  ctx.arc(x, y, 10, 0, 2 * Math.PI, false);
  ctx.closePath();
  ctx.fill();
}

function getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect();
  return {
    x: evt.clientX - rect.left,
    y: evt.clientY - rect.top
  };
}
canvas.addEventListener('mousemove', function(evt) {
  var mousePos = getMousePos(canvas, evt);
  x = mousePos.x;
  y = mousePos.y;
}, false);

function draw() {
  ctx.globalCompositeOperation = "source-over";
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  for (var i = 0; i < max; i++) {
    for (var j = 0; j < max; j++) {
      ctx.fillStyle = 'rgb(' + Math.floor(255 - 5.5 * i) + ',' + Math.floor(255 - 5.5 * j) + ',0)';
      ctx.fillRect(j * (canvas.width / max), i * (canvas.height / max), canvas.width / max, canvas.height / max);
    }
  }
  circle();
  setTimeout(draw, 10);
}
draw();
<canvas id="canvas"></canvas>

设置 canvas 的 CSS 样式将拉伸和挤压像素。这就是为什么你的圆圈变成了椭圆形。

而是设置 canvas 元素的宽度和高度。这实际上向 canvas 添加(或删除)像素以成为指定的大小。这将使您的圈子保持圆形。 ;-)

canvas.width=500;    // no need to add "px"
canvas.height=400;