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.
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.
Do I need to do something different to enable dragging in 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?
Try using this for android
e.touches[0].pageX
e.touches[0].pageY
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.