JSFiddle - React, Tailwind, and code Playground
by Josh Pullen
HTML
<div id="sketch">
<canvas id="paint"></canvas>
</div>
CSS
html, body {
width: 100%;
height: 100%;
margin:0px;
padding:0px;
overflow:hidden;
}
body {
position: relative
}
#sketch {
height: 100%;
}
JavaScript
(function() {
var canvas = document.getElementById('paint');
var ctx = canvas.getContext('2d');
var sketch = document.getElementById('sketch');
var sketch_style = getComputedStyle(sketch);
canvas.width = window.innerWidth; // TODO: fit for resolution
canvas.height = window.innerHeight;
var mouse = {x: 0, y: 0};
var last_mouse = {x: 0, y: 0};
/* Mouse Capturing Work */
canvas.addEventListener('mousemove', function(e) {
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
}, false);
/* Drawing on Paint App */
ctx.lineWidth = 5;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = 'blue';
canvas.addEventListener('mousedown', function(e) {
canvas.addEventListener('mousemove', onPaint, false);
}, false);
canvas.addEventListener('touchstart', function(e) {
canvas.addEventListener('touchmove', onPaint, false);
}, false);
canvas.addEventListener('mouseup', function() {
canvas.removeEventListener('mousemove', onPaint, false);
// TODO: Add sync code here!
}, false);
canvas.addEventListener('touchend', function() {
canvas.removeEventListener('touchmove', onPaint, false);
// TODO: Add sync code here!
}, false);
var onPaint = function() {
ctx.beginPath();
ctx.moveTo(last_mouse.x, last_mouse.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.closePath();
ctx.stroke();
};
}());