使用鼠标事件在画布上绘制一个圆圈

2023-11-26

我试图使用鼠标事件在画布上使用鼠标绘制一个圆圈,但它没有绘制任何内容:

tools.circle = function () {
var tool = this;
this.started = false;
this.mousedown = function (ev) {
tool.started = true;
tool.x0 = ev._x;
tool.y0 = ev._y;
ctx.moveTo(tool.x0,tool.y0);
};

this.mousemove = function (ev) {
var centerX = Math.max(tool.x0,ev._x) - Math.abs(tool.x0 - ev._x)/2;
var centerY = Math.max(tool.y0,ev._y) - Math.abs(tool.y0 - ev._y)/2;
var distance = Math.sqrt(Math.pow(tool.x0 - ev._x,2) + Math.pow(tool.y0 - ev._y));
context.circle(tool.x0, tool.y0, distance/2,0,Math.PI*2 ,true);
context.stroke();
};
};

我究竟做错了什么?


好吧,这段代码片段并没有告诉我们太多信息,但是您的代码中有一些明显的错误。 首先,DOM Event 对象没有 _x and _y特性。反而clientX and clientY or pageX and pageY。 要从当前事件对象获取相对鼠标坐标,您可以执行以下操作:

element.onclick = function(e) {
    var x = e.pageX - this.offsetLeft;
    var y = e.pageY - this.offsetTop;
}

接下来,canvas 的 2d 上下文没有名为的方法circle,但你可以自己写,也许是这样的:

var ctx = canvas.context;
ctx.fillCircle = function(x, y, radius, fillColor) {
    this.fillStyle = fillColor;
    this.beginPath();
    this.moveTo(x, y);
    this.arc(x, y, radius, 0, Math.PI*2, false);
    this.fill();
}

不管怎样,这里有一个测试 html 页面来测试这一点:http://jsfiddle.net/ArtBIT/kneDX/

我希望这有帮助。 干杯

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用鼠标事件在画布上绘制一个圆圈 的相关文章

随机推荐