[英]HTML5 canvas works fine on desktop browser but not on Android
I'm trying to make a canvas that the user can draw on, following this tutorial . 按照本教程 ,我正在尝试制作供用户绘制的画布。
Code as follows: 代码如下:
<canvas id="playSpace" width="500" height="300"></canvas>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
context=document.getElementById('playSpace').getContext("2d");
$('#playSpace').mousedown(function(e){
var mouseX=e.pageX - this.offsetLeft;
var mouseY=e.pageY - this.offsetTop;
paint=true;
addClick(e.pageX - this.offsetLeft,e.pageY-this.offsetTop);
redraw();
});
$('#playSpace').mousemove(function(e){
if(paint){
addClick(e.pageX - this.offsetLeft,e.pageY - this.offsetTop, true);
redraw();
}
});
$('#playSpace').mouseup(function(e){
paint=false;
});
$('#playSpace').mouseleave(function(e){
paint=false;
});
var clickX=new Array();
var clickY=new Array();
var clickDrag=new Array();
var paint;
function addClick(x,y,dragging)
{
clickX.push(x);
clickY.push(y);
clickDrag.push(dragging);
}
function redraw(){
context.clearRect(0,0,context.canvas.width,context.canvas.height);
context.strokeStyle="#df4b26";
context.lineJoin="round";
context.lineWidth=5;
for(var i=0;i<clickX.length;i++){
context.beginPath();
if(clickDrag[i] && i){
context.moveTo(clickX[i-1],clickY[i-1]);
}
else{
context.moveTo(clickX[i]-1,clickY[i]);
}
context.lineTo(clickX[i],clickY[i]);
context.closePath();
context.stroke();
}
}
</script>
I tested it in this JSFiddle and it works fine on Chrome on my desktop: clicking and dragging draws red lines. 我在此JSFiddle中对其进行了测试,它在桌面上的Chrome上运行良好:单击并拖动会绘制红线。
But when I open the same JSFiddle in Chrome on my Android phone, running Android 4.2.2, nothing happens: I drag my finger across the canvas but no lines appear. 但是,当我在运行Android 4.2.2的Android手机上的Chrome中打开相同的JSFiddle时,什么也没发生:我在画布上拖动手指,但没有出现任何线条。
Do I need to do something different to enable dragging in Android? 我需要做一些其他事情才能在Android中启用拖动吗?
A mobile device does not necessarily have mouse move events, it has touch events. 移动设备不一定具有鼠标移动事件,而是具有触摸事件。
Take a look at this answer: 看一下这个答案:
How to get continuous mousemove event when using android mobile browser? 使用Android移动浏览器时如何获取连续的mousemove事件?
Try using this for android 尝试将其用于android
e.touches[0].pageX
e.touches[0].pageY
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.