[英]Drawing a circle on the canvas using mouse events
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? 我究竟做错了什么?
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 _ x
and _ y
properties. 首先,DOM Event对象没有_ x
和_ y
属性。 but rather clientX
and clientY
or pageX
and pageY
. 而是clientX
和clientY
或pageX
和pageY
。 To get relative mouse coordinates from the current event object, you would do something like: 要从当前事件对象获取相对鼠标坐标,您可以执行以下操作:
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: 接下来,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();
}
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 干杯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.