<html>
<head>
<style>
body {
margin: 0
}
canvas {
width: 100vw;
height: 100vh;
border: solid 0px black
}
</style>
<title>Color Blocks</title>
</head>
<body>
<canvas width="500" height="500"></canvas>
</body>
<script>
let isDrawing = false;
let x = 0;
let y = 0;
const can = document.querySelector('canvas');
can.width = document.body.clientWidth;
can.height = document.body.clientHeight;
can.style.width = can.width +'px'
can.style.height = can.height +'px'
const context = can.getContext('2d');
document.addEventListener('keydown', e => {
switch (e.key) {
case 's':
let image = can.toDataURL("image/png").replace("image/png", "image/octet-stream");
window.location.href = image;
break;
default:
console.log(e)
}
});
can.addEventListener("mousedown", mouseDown, false);
can.addEventListener("mousemove", mouseMove, false);
can.addEventListener("touchstart", touchDown, false);
can.addEventListener("touchmove", touchMove, true);
can.addEventListener("touchend", touchUp, false);
document.body.addEventListener("mouseup", mouseUp, false);
document.body.addEventListener("touchcancel", touchUp, false);
function mouseDown(e) {
x = e.offsetX;
y = e.offsetY;
isDrawing = true;
}
function mouseMove(e) {
if (isDrawing === true) {
drawLine(context, x, y, e.offsetX, e.offsetY);
x = e.offsetX;
y = e.offsetY;
}
}
function mouseUp(e) {
if (isDrawing === true) {
drawLine(context, x, y, e.offsetX, e.offsetY);
x = 0;
y = 0;
isDrawing = false;
}
}
function touchDown(e) {
x = e.targetTouches[0].pageX - can.offsetLeft;
y = e.targetTouches[0].pageY - can.offsetTop;
isDrawing = true;
e.preventDefault();
return false;
}
function touchMove(e) {
if (isDrawing === true) {
deltaX = e.targetTouches[0].pageX - can.offsetLeft;
deltaY = e.targetTouches[0].pageY - can.offsetTop;
drawLine(context, x, y, deltaX, deltaY);
x = deltaX;
y = deltaY;
}
e.preventDefault();
return false;
}
function touchUp(e) {
e.preventDefault();
return false;
}
function drawCircle(context, x1, y1, x2, y2) {
context.beginPath();
context.fillStyle = '#' + Math.floor(Math.random() * 16777215).toString(16);
var a = x1 - x2;
var b = y1 - y2;
lineWidth = parseInt(Math.sqrt(a * a + b * b)) / 2;
context.arc(x1 - a / 2, y1 - b / 2, lineWidth, 0, 2 * Math.PI);
context.fill();
context.closePath();
}
function drawLine(context, x1, y1, x2, y2) {
//drawCircle(context, x1, y1, x2, y2);
//return;
context.beginPath();
context.strokeStyle = '#' + Math.floor(Math.random() * 16777215).toString(16);
var a = x1 - x2;
var b = y1 - y2;
context.lineWidth = parseInt(Math.sqrt(a * a + b * b));
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.stroke();
context.closePath();
}
</script>
</html>
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.