Mouse down to draw in it.
Sadly, this only works if it is the only post viewed.
JSFiddle was very useful in debugging this and getting it to work. I did the development on a PC, and tested the results immediately in a browser on a tablet and on my phone.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> | |
<script> | |
$(document).ready(function () { | |
$("#myCanvas2").height = 500; | |
$("#myCanvas2").width = 500; | |
$("#myCanvas2").mousemove(function (eventObject) { | |
//alert(event); | |
var ctx = this.getContext("2d"); | |
var clientRect = this.getBoundingClientRect(); | |
var x = (eventObject.pageX - clientRect.left); | |
var y = (eventObject.pageY - clientRect.top); | |
if (!isDrawing) { | |
return; | |
} | |
$("#x").text("mousemove " + x + " " + y); | |
if (lastLine != null) { | |
ctx.beginPath(); | |
ctx.moveTo(lastLine[0], lastLine[1]); | |
ctx.lineWidth = 5; | |
ctx.lineTo(x, y); | |
ctx.stroke(); | |
} | |
lastLine = [x, y]; | |
//$("#x").text("mousemove"); | |
}); | |
$("#myCanvas2").on({ 'touchstart': function () { isDrawing = true; | |
$("#x").text("touchstart"); | |
} }); | |
$("#myCanvas2").on({ 'touchend': function () { | |
isDrawing = false; | |
lastLine = null; | |
$("#x").text("touchend"); | |
} }); | |
$("#myCanvas2").on({ | |
'touchmove': function (eventObject) { | |
event.preventDefault(); | |
$("#x").text("touchmove"); | |
var ctx = this.getContext("2d"); | |
var clientRect = this.getBoundingClientRect(); | |
//alert(event.touches); | |
var x = (event.touches[0].pageX - clientRect.left); | |
var y = (event.touches[0].pageY - clientRect.top); | |
if (!isDrawing) { | |
return; | |
} | |
$("#x").text("touchmove " + x + " " + y); | |
if (lastLine != null) { | |
ctx.beginPath(); | |
ctx.moveTo(lastLine[0], lastLine[1]); | |
ctx.lineWidth = 5; | |
ctx.lineTo(x, y); | |
ctx.stroke(); | |
} | |
lastLine = [x, y]; | |
} | |
}); | |
$("#myCanvas2").on({ 'touchcancel': function () { isDrawing = false; lastLine = null; } }); | |
$("#myCanvas2").mousedown(function (eventObject) { | |
isDrawing = true; | |
}); | |
$("#myCanvas2").mouseup(function (mouseEvent) { | |
isDrawing = false; | |
lastLine = null; | |
}); | |
$("#myCanvas2").mouseleave(function (mouseEvent) { | |
isDrawing = false; | |
lastLine = null; | |
}); | |
$("#clearButton").click(function () { | |
$("#myCanvas2")[0].height = $("#myCanvas2")[0].height; | |
}); | |
}); | |
var isDrawing = false; | |
var lastLine = null; | |
</script> | |
<br /> | |
<canvas id="myCanvas2" style="border: solid;"></canvas> | |
<button id="clearButton">Clear</button> | |
<br /> | |
<div id="x"> | |
</div> | |
<div id="y"> | |
</div> |
No comments:
Post a Comment