Reputation: 295
I've been playing around with the HTML5 canvas lately and one of the things I've wanted to do is create a simple page with a canvas that'll draw a circle wherever you click. I have some code that looks like it should work, and I've been attempting to debug with some console output, but I've been unable to see any errors at the moment.
I'm using Codepen though, so I'm unsure how fully featured that console is, and I unfortunately can't use the dev console on my laptop at the moment (locked down school Chromebook).
Could someone take a look? I'll put the code in here and drop a link to the pen as well. Thanks!
HTML:
<canvas id="canvas" onclick="drawCircle(event)"></canvas>
CSS:
canvas {
position: relative;
background: #f1c40f;
width: 100%;
height: 100%;
}
JS:
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
function drawCircle(e) {
var pos = getCursorPosition(c, e);
var clickX = pos.x;
var clickY = pos.y;
ctx.fillStyle = "#2980b9";
ctx.beginPath();
ctx.arc(clickX, clickY, 10, 0, 2 * Math.PI);
ctx.fill();
console.log(clickX, clickY);
console.log("drawcircle");
}
function getCursorPosition(canvas, e) {
// Gets click position
rect = canvas.getBoundingClientRect();
console.log('getcursorpos');
return {
x: e.clientX - rect.left,
y: e.clientY - rect.top
};
}
Codepen link: https://codepen.io/wolverine1621/pen/gWvjgx
Any help is appreciated. It's probably something pretty simple but this is really my first time working with canvas, so any input is helpful!
Thanks!
Upvotes: 1
Views: 3118
Reputation: 32869
The issue is occurring because, you set the canvas's width
and height
using css.
You should rather set it using javascript, like so ...
c.width = window.innerWidth;
c.height = window.innerHeight;
and to make the canvas flexible, so that it maintains it's size, use ...
window.onresize = function() {
c.width = window.innerWidth;
c.height = window.innerHeight;
}
Here is the working codepen
Upvotes: 3
Reputation: 3781
A couple of things:
1) you are not setting a width and height for your canvas, so there is going to be distortion and the x/y values are going to be weird. Solution: set the width and height of the canvas to the window height and width
2) Your method for determining clickX and clickY is overly complicated. Solution: use event.clientX and event.clientY
After getting your context, set the width and height:
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
Note: I would also encourage you to remove the margin on the body in CSS
body { margin: 0 }
Now you can get rid of getCursorPosition (because it is giving you wrong values)
var clickX = e.clientX
var clickY = e.clientY
Upvotes: 2