I added an image to a canvas. I want to draw on the image, but when drawing a line, it does not appear above the mouse pointer. The canvas container has a method to verify the correct position of the mouse inside the canvas and it is correct, but the drawn line appears far below the mouse pointer. How can I make the drawing stroke, where is the mouse pointer?
public canvas() {
let x;
let y;
//we determine the location of the mouse within the canvas
$('#mycanvas').mousemove(function(e){
var rect = e.target.getBoundingClientRect();
x = e.clientX - rect.left; //x position within the element.
y = e.clientY - rect.top; //y position within the element.
console.log("X : " + x );
console.log("Y : " + y );
});
const canvas = <HTMLCanvasElement> document.querySelector("#mycanvas");
const ctx = canvas.getContext("2d");
//Agregamos imagen al canvas
const image = new Image();
image.src = 'assets/img/human.png';
image.onload = function(){
ctx.drawImage(image, 0, 0, 300, 150);
}
//paint
let painting = false;
//starting position
function startPosition(e) {
painting = true;
draw(e);
}
//final position
function finishedPosition() {
painting = false;
ctx.beginPath();
}
function draw(e) {
if(!painting) {
return;
}
ctx.lineWidth = 0.5;
ctx.lineCap = "round";
ctx.lineTo(x, y);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x, y);
}
//EventListeners
canvas.addEventListener("mousedown", startPosition);
canvas.addEventListener("mouseup", finishedPosition);
canvas.addEventListener("mousemove", draw)
}
Use this function and pass the event argument to it. to get absolute x,y on canvas element.
function getPosition(e) {
this.boundingRect = canvas.getBoundingClientRect(); // canvas = canvas element
return {
x : (e.targetTouches) ? e.targetTouches[0].pageX - this.boundingRect.x : e.offsetX,
y : (e.targetTouches) ? e.targetTouches[0].pageY - this.boundingRect.y : e.offsetY,
};
}
For optimization you can cache this.boundingRect
variable, because getBoundingClientRect operation is time consuming
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.