I've been working on this really basic drawing program for a while now and just can't seem to get it to work correctly.
The user can draw in the canvas element now, but things are somehow misaligned; the lines appear far from the cursor when you attempt to draw, and I'm not sure what's causing it.
Here's my code...
html
<div class="info">
<canvas id="canvas" height="480" width="640" style="border:1px solid #000000; width: 640px; height:480px; background-color: white">Please update your browser.</canvas>
<script src="paint.js"></script>
</div>
javascript
// paint.js
(function () {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
//resizing
//canvas.height = window.innerHeight;
//canvas.width = window.innerWidth;
//variables
var painting = false;
function startPosition(e) {
painting = true;
draw(e);
}
function endPosition() {
painting = false;
context.beginPath();
}
function draw(e) {
if (!painting) return;
context.lineWidth = 7;
context.lineCap = "round";
context.strokeStyle = "green";
context.lineTo(e.clientX, e.clientY);
context.stroke();
context.beginPath();
context.moveTo(e.clientX, e.clientY);
}
//EventListeners
canvas.addEventListener("mousedown", startPosition);
canvas.addEventListener("mouseup", endPosition);
canvas.addEventListener("mousemove", draw);
})();
change the clientX
and clientY
with offsetX
and offsetY
to get the right coords according to mouse position inside the element
you can read more about MouseEvent and figure out the differences between
clientX/Y
screenX/Y
offsetX/Y
try the snippet
// paint.js
(function () {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
//resizing
//canvas.height = window.innerHeight;
//canvas.width = window.innerWidth;
//variables
var painting = false;
function startPosition(e) {
painting = true;
draw(e);
}
function endPosition() {
painting = false;
context.beginPath();
}
function draw(e) {
if (!painting) return;
context.lineWidth = 4;
context.lineCap = "round";
context.strokeStyle = "green";
context.lineTo(e.offsetX, e.offsetY);
context.stroke();
context.beginPath();
context.moveTo(e.offsetX, e.offsetY);
}
//EventListeners
canvas.addEventListener("mousedown", startPosition);
canvas.addEventListener("mouseup", endPosition);
canvas.addEventListener("mousemove", draw);
})();
div {
width: 460px;
height: 460px;
border: 1px solid black;
}
<div class="info">
<canvas id="canvas" height="460" width="460" style="border:1px solid #000000; background-color: white">Please update your browser.</canvas>
<script src="paint.js"></script>
</div>