【发布时间】:2019-04-30 05:08:05
【问题描述】:
我正在尝试制作一个简单的绘图程序,并且正在慢慢实现。但是圆形工具有一个小问题。当用户单击并拖动时,圆圈会移动一点。矩形、椭圆形和多边形工具不会发生这种情况。如何解决这个问题?
这是画圆的代码
tools.circle = function () {
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.clearRect(0, 0, canvas.width, canvas.height);
var radius = Math.max(Math.abs(ev._x - tool.x0), Math.abs(ev._y - tool.y0)) / 2;
var x = Math.min(ev._x, tool.x0) + radius;
var y = Math.min(ev._y, tool.y0) + radius;
context.fillStyle = 'hsl(' + 360 * Math.random() + ', 85%, 50%)';
context.beginPath();
context.arc(x, y, radius, 0, Math.PI * 2, false);
context.stroke();
context.closePath();
context.fill();
};
this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
drawCanvas();
}
};
};
这是椭圆的工作代码
tools.oval = function () {
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.clearRect(0, 0, canvas.width, canvas.height);
var radius1 = Math.abs(ev._x - tool.x0);
var radius2 = Math.abs(ev._y - tool.y0);
var scaleX = radius1 / (Math.max(radius1, radius2));
var x = tool.x0 / scaleX;
var scaleY = radius2 / (Math.max(radius1, radius2));
var y = tool.y0 / scaleY;
context.fillStyle = 'hsl(' + 360 * Math.random() + ', 100%, 50%)';
context.save();
context.scale(scaleX, scaleY);
context.beginPath();
context.arc(x, y, Math.max(radius1, radius2), 0, 2 * Math.PI);
context.restore();
context.stroke();
context.closePath();
context.fill();
};
this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
drawCanvas();
}
};
};
如果圆不随鼠标在画布上移动,而是停留在起点并从那里拖出来,那就太好了。
【问题讨论】:
-
#SiezureWarning