【发布时间】:2021-08-14 00:43:16
【问题描述】:
我使用 javascript 制作了画布,它在桌面上运行良好,但在移动设备上无法运行。 在移动设备上,当我尝试绘制时,它只会滚动。请帮助我提供在移动设备上绘制的代码。 P.S:我已经从一些网站上获取了移动代码,但它仍然无法正常工作。 请告诉并解释如何在手机上绘制它的代码?谢谢!
编辑:当您运行代码段时,它会滞后于 StackOVERFLOW。请看这里:https://codepen.io/dikshatakyar/full/YzVgJWK 编辑 2:问题已解决。谢谢。
const canvas=document.querySelector('#draw');
const ctx=canvas.getContext('2d');
// all the drawing for the canvas in ctx
canvas.height=window.innerHeight;
canvas.width=window.innerWidth;
ctx.strokeStyle= '#51c9bb';
ctx.lineJoin='round';
ctx.lineCap='round';
ctx.lineWidth=30;
//flag
let isDrawing=false; //don't draw when mouse is just moving mouse w/o doing anything
//where to start a line from and then where to end it
let lastX=0;
let lastY=0;
let hue=0;
let direction=true;
function draw(e){
if(!isDrawing)
return; //only run in click and drag
console.log(e);
ctx.strokeStyle= `hsl(${hue},100%,50%)`;
ctx.beginPath();
ctx.moveTo(lastX,lastY); //start from
ctx.lineTo(e.offsetX,e.offsetY); //go to
ctx.stroke(); //to actually draw the path on canvas
[lastX,lastY]=[e.offsetX,e.offsetY];
// lastX=e.offsetX;
// lastY=e.offsetY;
hue++;
if(hue>=360){
hue=0;
}
if(ctx.lineWidth>=80 || ctx.lineWidth<=1){
direction=!direction;
}
if(direction)
ctx.lineWidth++;
else
ctx.lineWidth--;
}
canvas.addEventListener('mousemove',draw);
canvas.addEventListener('mousedown',(e)=>{
isDrawing=true;
[lastX,lastY]=[e.offsetX,e.offsetY];
});
canvas.addEventListener('mouseup',()=>isDrawing=false);
canvas.addEventListener('mouseout',()=>isDrawing=false);
//canvas on mobile
document.body.addEventListener("touchstart", function (e) {
if (e.target == canvas) {
e.preventDefault();
}
}, false);
document.body.addEventListener("touchend", function (e) {
if (e.target == canvas) {
e.preventDefault();
}
}, false);
document.body.addEventListener("touchmove", function (e) {
if (e.target == canvas) {
e.preventDefault();
}
}, false);
*{
margin: 0;
}
<canvas id="draw" width="800" height="800"></canvas>
【问题讨论】:
-
我无法运行代码。只是落后了
-
@GucciBananaKing99 是的,它落后于 stackoverflow,请在 codepen 上运行它或直接点击此链接:codepen.io/dikshatakyar/full/YzVgJWK
-
在移动设备上,您应该使用 touchmove,然后使用 targetTouches[0].clientX 和 clientY 作为坐标。
-
@ub_coding 是的,我已经更新了更改,但它仍然无法在 MOBILE 上运行。看看这里:codepen.io/dikshatakyar/full/YzVgJWK
-
像这样更改您的 touchmove 事件处理程序(有点骇人听闻,最终解决方案可能会使用 x 和 y 作为 draw 方法的参数){ if (e.target == canvas) { e.防止默认(); e.offsetX = e.tagetTouches[0].clientX; e.offsetY = e.tagetTouches[0].clientY;绘制(e)}
标签: javascript html css frontend