使用鼠标事件在画布上绘制圆 [英] 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();
};
};
我做错了什么?
推荐答案
好吧,这段代码片段没有告诉我们,但是代码中有一些明显的错误。
首先,DOM事件对象没有_ x
和_ y
属性。而是 clientX
和 clientY
或 pageX
和 pageY
。
要从当前事件对象获取相对鼠标坐标,您可以这样做:
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. but rather clientX
and clientY
or pageX
and 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;
}
接下来,canvas'2d上下文没有一个名为 circle
,但你可以写自己的,也许像:
Next, canvas' 2d context doesn't have a method called circle
, but you could write your own, maybe something like:
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/
我希望这有帮助。
Cheers
I hope this helps. Cheers
这篇关于使用鼠标事件在画布上绘制圆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!