【发布时间】:2021-01-30 16:08:50
【问题描述】:
我在画布上添加了一张图片。我想在图像上绘图,但是在绘制线条时,它没有出现在鼠标指针上方。画布容器有一个方法来验证鼠标在画布内的正确位置并且它是正确的,但是绘制的线出现在鼠标指针的下方。怎么画笔画,鼠标指针在哪里?
公共画布(){
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)
}
【问题讨论】:
-
可以发截图吗?
-
当然可以,但是你不会看到鼠标指针在哪里
标签: javascript html jquery typescript canvas