JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="paint" style="border:solid; ">Use any browser except Internet Explorer to draw on this canvas!</canvas>
JavaScript
//Canvas Drawing by Greg Ellis [email protected]
$(function() {
var letsdraw = false;
var theCanvas = document.getElementById('paint');
var ctx = theCanvas.getContext('2d');
theCanvas.width = 960;
theCanvas.height = 334;
var canvasOffset = $('#paint').offset();
$('#paint').mousemove(function(e) {
if (letsdraw === true) {
ctx.lineTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
ctx.stroke();
}
});
$('#paint').mousedown(function() {
// setup all of the properties for your line on mousedown, not mousemove
letsdraw = true;
ctx.strokeStyle = 'rgba(0,0,0,0.1)';
ctx.lineWidth = 3;
ctx.lineCap = 'round';
ctx.beginPath();
ctx.moveTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
});
$(window).mouseup(function() {
// bind to the window mouse up, that way if you mouse up and you're not over
// the canvas you'll still get the release of the drawing.
letsdraw = false;
});
});