我想要在我的 Canvas 上绘制类似椭圆选项的东西。我已经部分实现了这一点。问题是我无法获得圆的半径;目前我已将其硬编码为 15。此外,我想绘制一个椭圆(如在油漆中)而不是精确的圆。
这是我使用鼠标事件在 Canvas 上绘制圆圈的代码。请帮助我编写代码以实现上述要求。
function tool_circle() {
var tool = this;
this.started = false;
this.mousedown = function (ev) {
tool.started = true;
tool.x0 = ev._x;
tool.y0 = ev._y;
};
this.mousemove = function (ev) {
if (!tool.started) {
return;
}
context.fillStyle = 'red';
var distance = Math.sqrt(Math.pow(tool.x0 - ev._x, 2) + Math.pow(tool.y0 - ev._y));
context.beginPath();
context.arc(tool.x0, tool.y0,15, 0, Math.PI * 2, false);
context.stroke();
context.fill();
};
this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
img_update();
}
};
}
最佳答案
我会与markE的答案类似,但是使用贝塞尔曲线会绘制椭圆,但它不会为您提供您可能需要的确切半径。
为此,需要一个绘制手动椭圆的函数,而且相当简单 -
此函数将取 Angular 起点和终点并绘制椭圆 正是 在该边界内:
Live demo
function drawEllipse(x1, y1, x2, y2) {
var radiusX = (x2 - x1) * 0.5, /// radius for x based on input
radiusY = (y2 - y1) * 0.5, /// radius for y based on input
centerX = x1 + radiusX, /// calc center
centerY = y1 + radiusY,
step = 0.01, /// resolution of ellipse
a = step, /// counter
pi2 = Math.PI * 2 - step; /// end angle
/// start a new path
ctx.beginPath();
/// set start point at angle 0
ctx.moveTo(centerX + radiusX * Math.cos(0),
centerY + radiusY * Math.sin(0));
/// create the ellipse
for(; a < pi2; a += step) {
ctx.lineTo(centerX + radiusX * Math.cos(a),
centerY + radiusY * Math.sin(a));
}
/// close it and stroke it for demo
ctx.closePath();
ctx.strokeStyle = '#000';
ctx.stroke();
}
该演示也标记了矩形区域以显示椭圆正好在其中。画
要处理可让您绘制椭圆的鼠标操作,您可以执行以下操作:
var canvas = document.getElementById('myCanvas'),
ctx = canvas.getContext('2d'),
w = canvas.width,
h = canvas.height,
x1, /// start points
y1,
isDown = false; /// if mouse button is down
/// handle mouse down
canvas.onmousedown = function(e) {
/// get corrected mouse position and store as first point
var rect = canvas.getBoundingClientRect();
x1 = e.clientX - rect.left;
y1 = e.clientY - rect.top;
isDown = true;
}
/// clear isDown flag to stop drawing
canvas.onmouseup = function() {
isDown = false;
}
/// draw ellipse from start point
canvas.onmousemove = function(e) {
if (!isDown) return;
var rect = canvas.getBoundingClientRect(),
x2 = e.clientX - rect.left,
y2 = e.clientY - rect.top;
/// clear canvas
ctx.clearRect(0, 0, w, h);
/// draw ellipse
drawEllipse(x1, y1, x2, y2);
}
一个技巧可以是在主 Canvas 上创建一个顶部 Canvas 并在那里进行绘图。释放鼠标按钮后,将绘图传输到主 Canvas 。这样您就不必在绘制新形状时重新绘制所有内容。希望这可以帮助!
关于javascript - 使用鼠标事件在 HTML5 Canvas 上绘制圆/椭圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21594756/