Skip to content

Instantly share code, notes, and snippets.

@braska
Last active January 15, 2016 19:21
Show Gist options
  • Save braska/5e0ea6b3a5fe8e294640 to your computer and use it in GitHub Desktop.
Save braska/5e0ea6b3a5fe8e294640 to your computer and use it in GitHub Desktop.
Canvas Lukeboard
<html>
<head>
<meta charset="utf-8"/>
<title>HTML5 Canvas Drawing Board</title>
<script type="text/JavaScript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
body, html {
height: 100%;
}
#myCanvas {
cursor: crosshair;
position: fixed;
}
#cover {
position: fixed;
top: 100px;
left: 50px;
}
</style>
</head>
<body>
<img src="http://lorempixel.com/150/150/cats" id="cover">
<canvas id="myCanvas">
Sorry, your browser does not support HTML5 canvas technology.
</canvas>
<script>
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;
var imageObj = new Image();
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
var width = myCanvas.width;
var height = myCanvas.height;
imageObj.onload = function () {
ctx.drawImage(imageObj, 0, 0, width, height);
ctx.globalCompositeOperation = 'destination-out';
ctx.strokeStyle = 'rgba(255,0,0,255)';
};
// Mouse Event Handlers
if (myCanvas) {
var isDown = false;
var canvasX, canvasY;
ctx.lineWidth = 50;
$(myCanvas)
.on('mousedown touchstart', function (e) {
isDown = true;
ctx.beginPath();
canvasX = e.originalEvent.touches == undefined ? e.pageX - myCanvas.offsetLeft : e.originalEvent.touches[0].pageX;
canvasY = e.originalEvent.touches == undefined ? e.pageY - myCanvas.offsetLeft : e.originalEvent.touches[0].pageY;
ctx.moveTo(canvasX, canvasY);
})
.on('mousemove touchmove', function (e) {
console.log(e);
if (isDown !== false) {
canvasX = e.originalEvent.touches == undefined ? e.pageX - myCanvas.offsetLeft : e.originalEvent.touches[0].pageX;
canvasY = e.originalEvent.touches == undefined ? e.pageY - myCanvas.offsetLeft : e.originalEvent.touches[0].pageY;
ctx.lineTo(canvasX, canvasY);
ctx.stroke();
}
})
.on('mouseup touchend', function (e) {
isDown = false;
ctx.closePath();
});
}
// Disable Page Move
document.body.addEventListener('touchmove', function (evt) {
evt.preventDefault();
}, false);
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment