JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="can" width="400" height="400" > </canvas>
<div id="clr">
<div style="background-color:black;"></div>
<div style="background-color:red;"></div>
<div style="background-color:green;"> </div>
<div style="background-color:orange;"> </div>
</div>
<div id="tools">
<a href="#" id="clear" >Clear</a>
<a id="save" href="#">Save</a>
<a id="eraser" href="#">Eraser</a>
</div>
<span id="result" ></span>
<a class="attribution" href="http://motyar.blogspot.com/2010/04/drawing-on-web-with-canvas-and-jquery.html">From Moytar</a>
CSS
*{
margin:0;
-webkit-user-select: none;
font-family:sans-serif;
}
canvas{
cursor: crosshair;
border:black solid 1px;
display:block;
}
#clr div{
cursor:pointer;
cursor:hand;
width:40px;
height:40px;
float:left;
display:block;
margin-right:40px;
}
#clr{
margin-top: 20px;
display:block;
width:400px;
margin-left: 60px;
}
#tools{
display:block;
width:400px;
text-align:center;
margin-top: 20px;
padding-top:20px;
}
#tools a{
display:inline-block;
margin-top: 20px;
padding:10px;
}
.attribution{
display:block;
margin-top: 200px;
}
JavaScript
$(document).ready(function() {
var draw= false;
var canvas = document.getElementById("can");
var ctx = canvas.getContext("2d");
ctx.strokeStyle = 'red';
$("#can").mousedown(function(){draw=true;});
$("#can").mouseup(function(){draw=false;});
$("#can").mousemove(function(e) {
if(draw==true){
ctx.lineWidth = 5;
ctx.lineCap = "round";
ctx.beginPath();
ctx.moveTo(e.pageX,e.pageY);
ctx.lineTo(e.pageX+1,e.pageY+1);
ctx.stroke();
}
});
$("#clr > div").click(
function(){
ctx.strokeStyle = $(this).css("background-color");
});
$("#eraser").click(function(){
ctx.strokeStyle = '#fff';
});
$("#save").click(function(){
$("#result").append("<br /><br /><img src="+
canvas.toDataURL()+
" /><br /><a href="+canvas.toDataURL()+
" target='_blank'>show</a>");
});
$("#clear").click(function(){
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = "red";
ctx.fillStyle = "red";
}
);
});