Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save 0Charliecat/07be6137dbdb072f815bdd4a1ca6a46e to your computer and use it in GitHub Desktop.
Save 0Charliecat/07be6137dbdb072f815bdd4a1ca6a46e to your computer and use it in GitHub Desktop.
HTML5 Canvas Whiteboard (Touch and Mouse)

HTML5 Canvas Whiteboard (Touch and Mouse)

This whiteboard is touch & mouse friendly. It fills the page width & height so you can draw on the entire page. Nothing special, just experimenting with touch, and thought I'd share.

A Pen by Slovak_Cat on CodePen.

License.

<head>
<meta charset="utf-8" />
<title>HTML5 Canvas Drawing Board</title>
<script type="text/JavaScript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js?ver=1.4.2"></script>
</head>
<body>
<canvas id="myCanvas">
Sorry, your browser does not support HTML5 canvas technology.
</canvas>
</body>
</html>
window.onload = function() {
var myCanvas = document.getElementById("myCanvas");
var ctx = myCanvas.getContext("2d");
// Fill Window Width and Height
myCanvas.width = window.innerWidth;
myCanvas.height = window.innerHeight;
// Set Background Color
ctx.fillStyle="#fff";
ctx.fillRect(0,0,myCanvas.width,myCanvas.height);
// Mouse Event Handlers
if(myCanvas){
var isDown = false;
var canvasX, canvasY;
ctx.lineWidth = 5;
$(myCanvas)
.mousedown(function(e){
isDown = true;
ctx.beginPath();
canvasX = e.pageX - myCanvas.offsetLeft;
canvasY = e.pageY - myCanvas.offsetTop;
ctx.moveTo(canvasX, canvasY);
})
.mousemove(function(e){
if(isDown !== false) {
canvasX = e.pageX - myCanvas.offsetLeft;
canvasY = e.pageY - myCanvas.offsetTop;
ctx.lineTo(canvasX, canvasY);
ctx.strokeStyle = "#000";
ctx.stroke();
}
})
.mouseup(function(e){
isDown = false;
ctx.closePath();
});
}
// Touch Events Handlers
draw = {
started: false,
start: function(evt) {
ctx.beginPath();
ctx.moveTo(
evt.touches[0].pageX,
evt.touches[0].pageY
);
this.started = true;
},
move: function(evt) {
if (this.started) {
ctx.lineTo(
evt.touches[0].pageX,
evt.touches[0].pageY
);
ctx.strokeStyle = "#000";
ctx.lineWidth = 5;
ctx.stroke();
}
},
end: function(evt) {
this.started = false;
}
};
// Touch Events
myCanvas.addEventListener('touchstart', draw.start, false);
myCanvas.addEventListener('touchend', draw.end, false);
myCanvas.addEventListener('touchmove', draw.move, false);
// Disable Page Move
document.body.addEventListener('touchmove',function(evt){
evt.preventDefault();
},false);
};
* {
margin: 0;
padding: 0;
}
body, html {
height: 100%;
}
#myCanvas {
cursor: crosshair;
position: fixed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment