【发布时间】:2022-01-05 14:14:31
【问题描述】:
我正在画布上使用 HTML、CSS 和 JavaScript(JQuery) 创建一个绘图工具。
在桌面上,当我点击画布时它开始绘制,即使我释放点击并移动鼠标,它也会继续绘制(我希望它仅在我按住点击并移动鼠标时绘制)。
对于移动设备,它会在 2 次触摸后开始绘制(我不知道为什么)并按预期绘制,即仅当我拿着它时。但是这里的问题是,当我触摸其他地方时,它不是在我触摸的地方画一个点,而是从我之前停止的位置到当前位置画一条线(例如,如果我之前一次又一次地停在页面的左下角触摸页面的右上角开始,它会画一条线)。
通过查看其他答案,我添加了很多东西(相关与否我不知道),但它不起作用。请帮我解决这两个问题。谢谢。
这是删除我知道不会导致问题的部分后的 JS 代码:
$(document).ready(function(){
let color = "black";
let x;
let y;
let isPressed;
const canvas = $("canvas");
const colorElement = $("#color");
const ctx = canvas[0].getContext("2d");
const canvass = document.getElementById("myCanvas");
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
let prevX,prevY;
canvas.on("mousedown",(e)=>{
isPressed = true;
prevX = x;
prevY = y;
x = e.pageX - ctx.canvas.offsetLeft;
y = e.pageY - ctx.canvas.offsetTop;
});
$("document").on("mouseup",(e)=>{
isPressed = false;
x = undefined;
y = undefined;
});
canvas.on("mousemove",(e)=>{
if(isPressed){
e.preventDefault(); /*added this after looking at other answers*/
e.stopPropagation(); /*added this after looking at other answers*/
x = e.pageX - ctx.canvas.offsetLeft;
y = e.pageY - ctx.canvas.offsetTop;
drawCircle(x,y);
drawLine(prevX,prevY,x,y);
prevX = x;
prevY = y;
}
});
/*for the app to work on mobile devices*/
canvass.addEventListener("touchmove", function (e) {
var touch = e.touches[0];
var mouseEvent = new MouseEvent("mousemove", {
clientX: touch.clientX,
clientY: touch.clientY
});
canvass.dispatchEvent(mouseEvent);
}, false);
canvass.addEventListener("touchdown", function (e) {
var touch = e.touches[0];
var mouseEvent = new MouseEvent("mousedown", {
clientX: touch.clientX,
clientY: touch.clientY
});
canvass.dispatchEvent(mouseEvent);
}, false);
canvass.addEventListener("touchup", function (e) {
var touch = e.touches[0];
var mouseEvent = new MouseEvent("mouseup", {
clientX: touch.clientX,
clientY: touch.clientY
});
canvass.dispatchEvent(mouseEvent);
}, false);
function drawCircle(x,y){
ctx.beginPath();
ctx.arc(x,y,size,0,Math.PI * 2);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
}
function drawLine(x,y,x2,y2){
ctx.beginPath();
ctx.moveTo(x,y);
ctx.lineTo(x2,y2);
ctx.strokeStyle = color;
ctx.lineWidth = size*2;
ctx.stroke();
ctx.closePath();
}
colorElement.on("change",(e)=>{
color = e.target.value;
});
});
【问题讨论】:
标签: javascript jquery html5-canvas mouseevent