JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="paint" />
CSS
canvas { cursor: pointer; }
*.unselectable {
-moz-user-select: -moz-none;
-khtml-user-select: none;
-webkit-user-select: none;
/*
Introduced in IE 10.
See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
*/
-ms-user-select: none;
user-select: none;
}
#paint:active {
cursor:pointer;
}
JavaScript
$(function ()
{
var letsdraw = false;
var theCanvas = document.getElementById('paint');
var ctx = theCanvas.getContext('2d');
theCanvas.width = 420;
theCanvas.height = 420;
$('#paint').css('background', 'whitesmoke').addClass('unselectable')
var canvasOffset = $('#paint').offset();
$('#paint').mousemove(function (e)
{
tweakMouseMoveEvent(e);
if (letsdraw === true)
{
ctx.lineTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
ctx.stroke();
}
});
$('#paint').mousedown(function (e)
{
if (e.which === 1)
{
letsdraw = true;
ctx.beginPath();
ctx.moveTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
}
});
$(window).mouseup(function (e)
{
if (e.which === 1) letsdraw = false;
});
function tweakMouseMoveEvent(e)
{
// Check from jQuery UI for IE versions < 9
if ($.browser.msie && !(document.documentMode >= 9) && !event.button)
{
letsdraw = false;
}
// If left button is not set, set which to 0
// This indicates no buttons pressed
if (e.which === 1 && !letsdraw) e.which = 0;
}
});