javascript 使用鼠标事件在画布上画一个圆圈
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3814442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Drawing a circle on the canvas using mouse events
提问by Nitesh
I am trying to draw a circle using mouse on the canvas using mouse events, but it does not draw anything:
我正在尝试使用鼠标事件在画布上使用鼠标绘制一个圆圈,但它没有绘制任何内容:
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();
};
};
What am I doing wrong?
我究竟做错了什么?
采纳答案by ArtBIT
Well, this code snippet doesn't tell us much, but there are a couple of obvious errors in your code.
First, DOM Event object doesn't have _xand _yproperties. but rather clientXand clientYor pageXand pageY.
To get relative mouse coordinates from the current event object, you would do something like:
好吧,这段代码片段并没有告诉我们太多,但是您的代码中有几个明显的错误。首先,DOM Event 对象没有 _x和 _y属性。而是clientXandclientY或pageXand pageY。要从当前事件对象获取相对鼠标坐标,您可以执行以下操作:
element.onclick = function(e) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
}
Next, canvas' 2d context doesn't have a method called circle, but you could write your own, maybe something like:
接下来,画布的 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();
}
Anyhow, here's a test html page to test this out: http://jsfiddle.net/ArtBIT/kneDX/
无论如何,这里有一个测试 html 页面来测试这个:http: //jsfiddle.net/ArtBIT/kneDX/
I hope this helps. Cheers
我希望这有帮助。干杯

