JSFiddle - React, Tailwind, and code Playground
by cgack
HTML
<!DOCTYPE html>
<html>
<body>
<div id="content">
<canvas id="canvas" height="500" width="500"></canvas>
</div>
</body>
</html>
CSS
#content { height: 500px; width: 500px; margin: 0 auto; }
#canvas{ border: solid black 1px; }
JavaScript
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
var draw = {
isDrawing: false,
mousedown: function(coordinates) {
ctx.beginPath();
ctx.moveTo(coordinates.x, coordinates.y);
this.isDrawing = true;
},
mousemove: function(coordinates) {
if (this.isDrawing) {
ctx.lineTo(coordinates.x, coordinates.y);
ctx.stroke();
}
},
mouseup: function(coordinates) {
this.isDrawing = false;
ctx.lineTo(coordinates.x, coordinates.y);
ctx.stroke();
ctx.closePath();
},
touchstart: function(coordinates) {
ctx.beginPath();
ctx.moveTo(coordinates.x, coordinates.y);
this.isDrawing = true;
},
touchmove: function(coors) {
if (this.isDrawing) {
ctx.lineTo(coordinates.x, coordinates.y);
ctx.stroke();
}
},
touchend: function(coors) {
if (this.isDrawing) {
this.touchmove(coordinates);
this.isDrawing = false;
}
}
};
function setupDraw(e) {
var cnt = document.getElementById("content");
var coordinates = {};
if (e.targetTouches){
coordinates = {
x: e.targetTouches[0].pageX - cnt.offsetLeft,
y: e.targetTouches[0].pageY - cnt.offsetTop
};
} else {
coordinates = {
x: e.pageX - cnt.offsetLeft,
y: e.pageY - cnt.offsetTop
};
}
draw[e.type](coordinates);
};
window.addEventListener("mousedown", setupDraw, false);
window.addEventListener("mousemove", setupDraw, false);
window.addEventListener("mouseup", setupDraw, false);
window.addEventListener("touchstart", setupDraw, false);
window.addEventListener("touchmove", setupDraw, false);
window.addEventListener("touchend", setupDraw, false);
document.body.addEventListener("touchmove", function(e) {
e.preventDefault();
}, false);