Skip to content

Instantly share code, notes, and snippets.

@cybear
Created March 14, 2011 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cybear/869824 to your computer and use it in GitHub Desktop.
Save cybear/869824 to your computer and use it in GitHub Desktop.
canvas drawing test
<!DOCTYPE HTML>
<html>
<head>
<title>Mobile Device</title>
<script type="text/javascript">
document.addEventListener('touchmove', function(e) {e.preventDefault();});
/* Based loosely on source code from http://dev.opera.com/articles/view/html5-canvas-painting/ */
function DrawingCanvas (options) {
var canvas, context, that=this,tool,offsetTop,offsetLeft;
function init() {
canvas = document.getElementById('drawing');
context = canvas.getContext('2d');
context.strokeStyle=options.strokeStyle||'red';
context.lineWidth=options.lineWidth||22;
context.lineCap='round';
offsetLeft=canvas.offsetLeft;
offsetTop=canvas.offsetTop;
tool = new pencil();
canvas.addEventListener('touchstart', touchHandler, false);
canvas.addEventListener('touchmove', touchHandler, false);
canvas.addEventListener('touchend', touchHandler, false);
}
function touchHandler(e) {
e.preventDefault();
var changedTouches=e.changedTouches,
pushEvent = function() {
for (var i=0;i<changedTouches.length;i++) {
var t=changedTouches.item(i);
tool[e.type]&&tool[e.type]({x:t.clientX-offsetLeft,y:t.clientY-offsetTop,id:t.identifier});
}
};
pushEvent();
}
var pencil = function () {
var self = this;
this.started = false;
this.touchstart = function(ev){
context.beginPath();
context.moveTo(ev.x,ev.y);
self.started=true;
};
this.touchmove = function(ev){
if (self.started) {
context.lineTo(ev.x,ev.y);
context.stroke();
}
};
this.touchend = function(ev) {
if (self.started) {
self.started=false;
}
};
};
that.clear=function(){
context.clearRect(0, 0, canvas.width, canvas.height);
};
init(options);
return that;
};
</script>
<style>
canvas#drawing{
position:absolute;
left:0;
top:0px;
}
</style>
<meta name="viewport" content="width=device-width, height=device-height, user-scalable=no" />
</head>
<body style="background-color:#ccc">
<canvas id="drawing" width=1024 height=636></canvas>
<script>
dc = new DrawingCanvas({
strokeStyle:'#000000',
lineWidth:2
});
</script>
</body>
</html>
@cybear
Copy link
Author

cybear commented Mar 14, 2011

Disclaimer: Ugly code :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment