<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="300" style="border:1px solid #d3d3d3;" onmousedown="generate()">
</canvas>
<input type="color" id="mycolor1" style="position:absolute;left:650px;top:20px;" value="#ff0000">
<script>
let state = 0;
let x1 = 0;
let y1 = 0;
let x2 = 0;
let y2 = 0;
function generate(){
let c = document.getElementById("myCanvas");
let ctx = c.getContext("2d");
let color1 = document.getElementById("mycolor1").value;
ctx.strokeStyle = color1;
if (state == 0){
x1 = event.pageX;
y1 = event.pageY;
if (x2!=0){
ctx.beginPath();
ctx.lineTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
ctx.fillStyle = color1;
ctx.fillRect(x1,y1, 25,25);
state = 1;
}
else
{
ctx.beginPath();
x2 = event.pageX;
y2 = event.pageY;
ctx.lineTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
ctx.fillStyle = color1;
ctx.fillRect(x2,y2, 25,25);
state = 0;
}
}
</script>
</body>
</html>
|