Reputation:
I have a project here that I'm working on so that using canvas I can try where the user is clicking. I am trying to draw a 10px circle - just small enough to see where the user has clicked on the canvas and as well as move to where the user has click and follow the cursor. Below is my code but the circle is not showing for some reason. I'm still somewhat new to canvas and JavaScript and any help is appreciated.
var cn = document.getElementById("main");
var c = cn.getContext("2d");
var mouse = {x:150, y:0};
window.addEventListener('mousedown', mHandler);
function mHandler(event) {
//mouse.x = event.clientX;
//mouse.y = event.clientY;
mouse.x = event.pageX;
mouse.y = event.pageY;
};
function main() {
c.clearRect(0, 0, cn.width, cn.height);
ctx.beginPath();
ctx.arc(0, 0, 0, 0, 2 * Math.PI);
ctx.stroke();
c.fillRect(mouse.x, mouse.y, 50, 50);
}
setInterval(main, 1000 / 60);
<p>Click on the Canvas!</p>
<canvas id="main" height="300" width="300" style="border: 1px solid black"></canvas>
Upvotes: 0
Views: 97
Reputation: 168863
You're drawing a circle of radius 0 at 0 x 0.
I'm using ctx.save()
/ctx.translate()
/ctx.restore()
here to mutate the transformation matrix of the context first, so we're still drawing at 0x0 in that matrix. (It makes additional transformations a little easier to wrap one's head around.)
(You could also just ctx.arc(mouse.x, mouse.y, 50, ...)
.)
In addition, you want to use offsetX
/offsetY
so you get the mouse coordinate relative to the canvas, not the page.
var cn = document.getElementById("main");
var ctx = cn.getContext("2d");
var mouse = { x: 150, y: 0 };
window.addEventListener("mousedown", mHandler);
function mHandler(event) {
mouse.x = event.offsetX;
mouse.y = event.offsetY;
}
function main() {
ctx.clearRect(0, 0, cn.width, cn.height);
ctx.save();
ctx.translate(mouse.x, mouse.y);
ctx.beginPath();
ctx.arc(0, 0, 50, 0, 2 * Math.PI);
ctx.stroke();
ctx.restore();
ctx.fillRect(mouse.x, mouse.y, 5, 5);
}
setInterval(main, 1000 / 60);
<p>Click on the Canvas!</p>
<canvas id="main" height="300" width="300" style="border: 1px solid black"></canvas>
Upvotes: 1