JSFiddle - React, Tailwind, and code Playground
HTML
<br />
<div id="sketch">
<canvas id="paint" width="700" height="700"></canvas>
</div>
<h2>Painting Editor</h2>
<br />
<div align="center">
<label>Line <input type="radio" name="Shape" value="Line" id="Line" checked /> </label>
<label>Rectangle <input type="radio" name="Shape" value="Rectangle" id="Rectangle" /> </label>
<label>Circle <input type="radio" name="Shape" value="Circle" id="Circle" /> </label>
JavaScript
var canvas = document.querySelector('#paint');
var context = canvas.getContext('2d');
var sketch = document.querySelector('#sketch');
var sketch_style = getComputedStyle(sketch);
// Pase into integer of Canvas size
canvas.width = parseInt(sketch_style.getPropertyValue('width'));
canvas.height = parseInt(sketch_style.getPropertyValue('height'));
// Creating a tmp canvas
var tmp_canvas = document.createElement('canvas');
var tmp_context = tmp_canvas.getContext('2d');
tmp_canvas.id = 'tmp_canvas';
tmp_canvas.width = canvas.width;
tmp_canvas.height = canvas.height;
sketch.appendChild(tmp_canvas);
// Mouse Position Setting
var mouse = { x: 0, y: 0 };
var last_mouse = { x: 0, y: 0 };
/* Drawing on Paint*/
tmp_context.lineWidth = 4;
tmp_context.lineJoin = 'round';
tmp_context.lineCap = 'round';
tmp_context.strokeStyle = 'Red';
tmp_context.fillStyle = 'Red';
var shape = '';
document.querySelector('#Line').onchange = function () {
if (this.checked)
shape = 'Line';
tmp_canvas.style.display = 'block';
}
/* Mouse Capturing Work */
tmp_canvas.addEventListener('mousemove', function (e) {
mouse.x = typeof e.offsetX === 'undefined' ? e.offsetX : e.layerX;
mouse.y = typeof e.offsetY === 'undefined' ? e.offsetY : e.layerY;
});
tmp_canvas.addEventListener('mousedown', function (e) {
tmp_canvas.addEventListener('mousemove', onLine);
mouse.x = typeof e.offsetX === 'undefined' ? e.offsetX : e.layerX;
mouse.y = typeof e.offsetY === 'undefined' ? e.offsetY : e.layerY;
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
onLine();
});
tmp_canvas.addEventListener('mouseup', function () {
tmp_canvas.removeEventListener('mousemove', onLine);
// Writing down to real canvas now
context.drawImage(tmp_canvas, 0, 0);
// Clearing tmp...