Files
JavaScript-from-Beginner-to…/Chapter 14/Code Samples/ch14-canvas-draw-mouse.html
T
2021-11-25 14:40:42 +01:00

64 lines
1.5 KiB
HTML
Executable File

<html>
<head>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<input type="color" id="bgColor" />
<br>
<img src="" width="300" height="200" id="holder" />
<input type="button" id="save" value="save" />
<script>
window.onload = init;
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
canvas.width = 700;
canvas.height = 700;
let pos = {
x: 0,
y: 0,
};
let bgColor = "red";
let bgC = document.getElementById("bgColor");
bgC.addEventListener("change", function () {
bgColor = event.target.value;
});
document.getElementById("save").addEventListener("click", function () {
let dataURL = canvas.toDataURL();
console.log(dataURL);
document.getElementById("holder").src = dataURL;
});
function init() {
canvas.addEventListener("mousemove", draw);
canvas.addEventListener("mousemove", setPosition);
canvas.addEventListener("mouseenter", setPosition);
}
function draw(e) {
if (e.buttons !== 1) return;
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
setPosition(e);
ctx.lineTo(pos.x, pos.y);
ctx.strokeStyle = bgColor;
ctx.lineWidth = 10;
ctx.lineCap = "round";
ctx.stroke();
}
function setPosition(e) {
pos.x = e.pageX;
pos.y = e.pageY;
}
</script>
</body>
</html>