'How to calibrate the pencil line with the canvas?
I am using html canvas in my sketchpad project and when i use try to draw on the canvas my line is forming at other coordinates inside the canvas different from my mouse pointer coordinates . According to my guess this bug has something to do with the position or width or height of my canvas because at the top-left corner the line and the pointer are at the same coordinates . I just started using js , can anyone help me solve out this problem ?
heres my js code
pencil.onclick = function(){
console.log('pencil clicked');
function pencil_draw(){
console.log('pencil selected');
var isDrawing = false;
var x = 0;
var y = 0;
canvas.addEventListener('mousedown',e=>{
console.log('mousedown activated');
x = e.offsetX;
y = e.offsetY;
isDrawing = true;
});
canvas.addEventListener('mousemove',e=>{
if(isDrawing == true){
console.log('mousemove activated');
drawline(context,x,y,e.offsetX,e.offsetY);
x = e.offsetX;
y = e.offsetY;
}
});
canvas.addEventListener('mouseup',e=>{
if(isDrawing == true){
console.log('mouseup activated');
drawline(context,x,y,e.offsetX,e.offsetY);
x=0;
y=0;
isDrawing = false;
}
})
function drawline(context,x,y,x1,y1){
context.beginPath();
context.strokeStyle = "black";
context.lineWidth = "2";
context.moveTo(x, y);
context.lineTo(x1, y1);
context.stroke();
context.closePath();
}
}
pencil_draw();
}
heres my css for the canvas
.canvasbox #canvas{
width:500px;
height:500px;
}
HTML of canvas
<section class="canvasbox">
<canvas id="canvas"></canvas>
</section>
heres my project link if anyone wants to check the whole code , its very early so there are no media query in it https://github.com/sharmaachintya08/sketchpad/tree/calibrate
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
