my problem at the moment is that the circle does not appear at all when the page is loaded. It only appears when clicked on the place where the circle is and disappears when clicked somewhere outside. (link to the fiddle below)
I used 'mousedown' event in 'addEventListener' method. Variable 'distance' stands for the distance between the coordinates of cursor and the circle center.
canvas.addEventListener('mousedown', function(evt) {
mousePos = getMousePos(canvas, evt);
var distance = Math.sqrt( Math.pow((mousePos.x - 100), 2) + Math.pow((mousePos.y - 300), 2) ) ;
if (distance <= 50 && distance >= 0) {
console.log('clicked on the circle');
}
}, false);
The result of the script should go like this:
Here's fiddle: fiddle (click at 'mouse position = 100; 300'[more or less] to see the circle)
Thanks in advance!!
A few glitches in your code:
A Demo: http://jsfiddle.net/m1erickson/LQ2ak/
After onload: draw the circle on the screen
// define the circle
// (we need this info for hit-testing later)
var cx=100;
var cy=300;
var radius=50;
// draw the circle so it appears onload
context.arc(cx,cy,radius,0, 2*Math.PI);
context.closePath(); // this makes a closed circle instead of 360 arc
context.fillStyle = 'green';
context.fill();
context.strokeStyle = 'green';
context.stroke();
In writeMessage: only clear the canvas where the message is being drawn
context.clearRect(0, 0, canvas.width, 25);
In mousedown: see if the mouse is inside the circle. If yes, clear the canvas.
// hit-test the circle
// this method does not use "expensive" Math.sqrt
function mouseIsInsideCircle(mouseX,mouseY,cx,cy,radius){
var dx=mouseX-cx;
var dy=mouseY-cy;
return(dx*dx+dy*dy<=radius*radius);
}
canvas.addEventListener('mousedown', function(evt) {
var mousePos = getMousePos(canvas, evt);
var mouseX=mousePos.x;
var mouseY=mousePos.y;
// if the mouse is inside the circle
if(mouseIsInsideCircle(mouseX,mouseY,cx,cy,radius)){
// erase the canvas
context.clearRect(0,25,canvas.width,canvas.height);
}
}, false);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.