Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
141
rated 0 times [  144] [ 3]  / answers: 1 / hits: 20523  / 14 Years ago, tue, september 28, 2010, 12:00:00

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?


More From » html

 Answers
15

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;
}


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();
}


Anyhow, here's a test html page to test this out: http://jsfiddle.net/ArtBIT/kneDX/



I hope this helps.
Cheers


[#95476] Saturday, September 25, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
antoinette

Total Points: 206
Total Questions: 99
Total Answers: 95

Location: Guam
Member since Tue, Nov 29, 2022
2 Years ago
;