Skip to content

Instantly share code, notes, and snippets.

@movahhedi
Created July 30, 2024 13:08
Show Gist options
  • Save movahhedi/2266e123f6cff2411db279a09e3a610e to your computer and use it in GitHub Desktop.
Save movahhedi/2266e123f6cff2411db279a09e3a610e to your computer and use it in GitHub Desktop.
A simple drawing canvas in pure JS
<html>
<script type="text/javascript">
let canvas,
ctx,
flag = false,
prevX = 0,
currentX = 0,
prevY = 0,
currentY = 0,
dotFlag = false,
x = "black",
y = 2,
canvasImage;
function init() {
canvas = document.getElementById("can");
ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
canvasImage = document.getElementById("canvasImage");
canvas.addEventListener("mousemove", (e) => findXY("move", e), false);
canvas.addEventListener("mousedown", (e) => findXY("down", e), false);
canvas.addEventListener("mouseup", (e) => findXY("up", e), false);
canvas.addEventListener("mouseout", (e) => findXY("out", e), false);
}
function draw() {
ctx.beginPath();
ctx.moveTo(prevX, prevY);
ctx.lineTo(currentX, currentY);
ctx.strokeStyle = x;
ctx.lineWidth = y;
ctx.stroke();
ctx.closePath();
}
function erase() {
ctx.clearRect(0, 0, w, h);
canvasImage.style.display = "none";
}
function save() {
canvasImage.style.border = "2px solid";
let dataUrl = canvas.toDataURL();
canvasImage.src = dataUrl;
canvasImage.style.display = "inline";
const link = document.createElement("a");
link.download = "filename.png";
link.href = dataUrl;
link.click();
}
function findXY(res, e) {
if (res == "down") {
prevX = currentX;
prevY = currentY;
currentX = e.clientX - canvas.offsetLeft;
currentY = e.clientY - canvas.offsetTop;
flag = true;
dotFlag = true;
if (dotFlag) {
ctx.beginPath();
ctx.fillStyle = x;
ctx.fillRect(currentX, currentY, 2, 2);
ctx.closePath();
dotFlag = false;
}
} else if (res == "up" || res == "out") {
flag = false;
} else if (res == "move" && flag) {
prevX = currentX;
prevY = currentY;
currentX = e.clientX - canvas.offsetLeft;
currentY = e.clientY - canvas.offsetTop;
draw();
}
}
</script>
<body onload="init()">
<canvas id="can" width="400" height="400"
style="position: absolute; top: 10%; left: 10%; border: 2px solid"></canvas>
<img id="canvasImage" style="position: absolute; top: 10%; left: 52%" style="display: none" />
<input type="button" value="save" id="btn" size="30" onclick="save()"
style="position: absolute; top: 55%; left: 10%" />
<input type="button" value="clear" id="clr" size="23" onclick="erase()"
style="position: absolute; top: 55%; left: 15%" />
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment