无论如何我都画不出一个合适的圆。我总是得到一个椭圆。下面是向您展示我的意思的示例代码:
function canvasClicked(number) {
var c = "canvas" + number;
var canvas = document.getElementById(c);
var context = canvas.getContext("2d");
var centerX = 150;
var centerY = 75;
context.beginPath();
context.arc(centerX, centerY, 70, 0, Math.PI * 2);
context.lineWidth = 10;
context.strokeStyle = "red";
context.stroke();
}
#canvas1 {
width: 200px;
height: 200px;
border: 1px solid black;
}
<canvas id="canvas1" onclick="canvasClicked(1)"></canvas>
我试图找出问题的原因,但没有成功。我知道 centerX 和 centerY 应该等于 element.width/2 和 element.height/2 但这给我带来了更尴尬的结果,将椭圆从盒子的中心移开。
最佳答案
问题是这样的:
#canvas1 {
width: 200px;
height: 200px;
border: 1px solid black;
}
使用时:
<canvas id="canvas1" onclick="canvasClicked(1)"></canvas>
或者更准确地说:可见的 css 尺寸与底层 Canvas 尺寸不同。因为没有将它们设置为元素的属性:
<canvas id="canvas1" onclick="canvasClicked(1)" width="200" height="200"></canvas>
将导致 Canvas 使用默认值 300x150px。
演示:http://jsbin.com/geralevi/1/
进一步引用:https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Basic_usage
Note: If your renderings seem distorted, try specifying your width and height attributes explicitly in the attributes, and not using CSS.
关于javascript - 无法使用 Canvas 绘制正确的圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24735777/