<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas</title>
</head>
<body>
<canvas width="1000" height="500" id="canvas"></canvas>
<div>
<button onclick="color='yellow'">yellow</button>
<button onclick="color='green'">green</button>
<button onclick="color='white'">white</button>
<button onclick="lineWidth=5">5px</button>
<button onclick="lineWidth=2">2px</button>
<button onclick="lineWidth=1">1px</button>
</div>
</body>
<script>
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
ctx.fillStyle = "black";
ctx.fillRect(0, 0, 1000, 500)
let color = "#fff";
let lineWidth = 1;
let onoff = false;
let oldx = 0;
let oldy = 0;
canvas.addEventListener("mousedown", down, false);
canvas.addEventListener("mouseup", up);
canvas.addEventListener("mousemove", move);
function down(event) {
onoff = true;
oldx = event.x;
oldy = event.y;
}
function up() {
onoff = false;
}
function move(event) {
if (onoff) {
let x = event.x;
let y = event.y;
ctx.beginPath();
ctx.moveTo(oldx, oldy);
ctx.strokeStyle = color;
ctx.lineWidth = lineWidth;
ctx.lineCap = "round";
ctx.lineTo(x, y);
ctx.stroke();
oldx = x;
oldy = y;
}
}
</script>
<style>
* {
margin: 0;
padding: 0;
}
</style>
</html>
每日一练(一)HTML5-canvas制作绘画板
最新推荐文章于 2024-04-04 20:56:51 发布