Skip to content

Instantly share code, notes, and snippets.

@goker-dev
Created January 5, 2013 19:56
Show Gist options
  • Save goker-dev/4463326 to your computer and use it in GitHub Desktop.
Save goker-dev/4463326 to your computer and use it in GitHub Desktop.
A CodePen by goker cebeci. click to draw - HTML5 canvas drawing with mouse and touch events.
<canvas id="canvas"></canvas>
<div id="go">[ CLICK/TAP TO DRAW ]</div>
function $(el) {
return document.getElementById(el.replace(/#/, ''));
}
;
var canvas = $('#canvas');
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
var context = canvas.getContext('2d');
var start = function(coors) {
context.beginPath();
context.moveTo(coors.x, coors.y);
this.isDrawing = true;
};
var move = function(coors) {
if (this.isDrawing) {
context.strokeStyle = "#fff";
context.lineJoin = "round";
context.lineWidth = 3;
context.lineTo(coors.x, coors.y);
context.stroke();
}
};
var stop = function(coors) {
if (this.isDrawing) {
this.touchmove(coors);
this.isDrawing = false;
}
};
var drawer = {
isDrawing: false,
mousedown: start,
mousemove: move,
mouseup: stop,
touchstart: start,
touchmove: move,
touchend: stop
};
var draw = function(e) {
var coors = {
x: e.clientX || e.targetTouches[0].pageX,
y: e.clientY || e.targetTouches[0].pageY
};
drawer[e.type](coors);
}
canvas.addEventListener('mousedown', draw, false);
canvas.addEventListener('mousemove', draw, false);
canvas.addEventListener('mouseup', draw, false);
canvas.addEventListener('touchstart', draw, false);
canvas.addEventListener('touchmove', draw, false);
canvas.addEventListener('touchend', draw, false);
var go = function(e) {
this.parentNode.removeChild(this);
draw(e);
};
$('#go').addEventListener('mousedown', go, false);
$('#go').addEventListener('touchstart', go, false);
// prevent elastic scrolling
document.body.addEventListener('touchmove', function(e) {
e.preventDefault();
}, false);
// end body:touchmove
window.onresize = function(e) {
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
};
html, body {
margin: 0;
padding: 0;
height: 100%;
color: #fff;
font-family: monospace;
font-size: 40px;
background: #000;
overflow: hidden;
}
div {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
line-height: 300px;
z-index: 10;
text-align: center;
text-shadow: 0 0 3px #fff;
cursor: pointer;
}
@amiroveisi
Copy link

amiroveisi commented Dec 2, 2018

it's nice sample, however it gets kind of laggy after i keep drawing using touch for a few seconds (it draws straight lines instead of curves).
im using Surface Pro 4 and Google Chrome to test.
But it's completely fine when i draw with mouse.

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