JSFiddle - React, Tailwind, and code Playground
by m1erickson
HTML
Width:<input id="width" value="400" onkeyup="return setSize()" />
<br />
Height:<input id="height" value="400" onkeyup="return setSize()" />
<br />
Line width:<input id="lWidth" value="5" onkeyup="return setWidth()" />
<br />
<canvas id="canvas" width="500" height="400"></canvas>
<canvas id="canvas2" width="500" height="400"></canvas>
</body>
CSS
body {
font-family:sans-serif;
font-size:14px;
line-height:25px;
}
#canvas, #canvas2 {
position:absolute;
left:180px;
top:0px;
border-width:1px;
border-style:solid;
border-radius:1px;
border-color:#666666;
cursor:default !important;
}
input {
border-radius:3px;
border-width:1px;
border-style:solid;
border-color:#000000;
padding:2px;
font-size:100%;
position:absolute;
left:101px;
width:69px;
}
JavaScript
var x;
var xStart;
var y;
var yStart;
var clicked = false;
var lWidth;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var canvas2 = document.getElementById("canvas2");
var context2 = canvas2.getContext("2d");
context.strokeStyle = "black";
context.lineCap = "round";
setWidth();
setSize();
canvas2.addEventListener("mousedown", startLine);
canvas2.addEventListener("mouseup", drawLine);
canvas2.addEventListener('mousemove', function (evt) {
var rect = canvas2.getBoundingClientRect();
x = evt.clientX - rect.left;
y = evt.clientY - rect.top;
if (clicked) {
canvas2.width = canvas2.width;
console.log(xStart);
// add beginPath so previous context2.rect's are dismissed
context2.beginPath();
context2.rect(xStart, yStart, x - xStart, y - yStart);
context2.stroke();
}
}, false);
function startLine() {
context.beginPath();
xStart = x;
yStart = y;
clicked = true;
}
function drawLine() {
clicked = false;
context.rect(xStart, yStart, x - xStart, y - yStart);
context.stroke();
}
function setSize() {
canvas.width = document.getElementById("width").value;
canvas2.width = document.getElementById("width").value;
canvas.height = document.getElementById("height").value;
canvas2.height = document.getElementById("height").value;
context.strokeStyle = "black";
context.lineCap = "round";
setWidth();
}
function setWidth() {
lWidth = document.getElementById('lWidth').value * 1.0;
context.lineWidth = lWidth;
}