HTML 代码:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript 画板</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<div>
<canvas id="myCanvas" width="500" height="500"></canvas>
</div>
<div>
<button onclick="setColor('red')">红色</button>
<button onclick="setColor('green')">绿色</button>
<button onclick="setColor('blue')">蓝色</button>
<button onclick="setColor('black')">黑色</button>
<button onclick="clearCanvas()">清除画布</button>
</div>
<script src="paint.js"></script>
</body>
</html>
在 HTML 中,我们创建了一个 canvas 元素和一些按钮用于设置画笔颜色和清空画布。canvas 元素用于绘制图像。
JavaScript 代码(保存在 paint.js 文件中):
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var color = "black";
var painting = false;
function setColor(newColor) {
color = newColor;
}
function startPainting() {
painting = true;
}
function stopPainting() {
painting = false;
}
function draw(event) {
if (!painting) {
return;
}
context.beginPath();
context.arc(event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop, 10, 0, Math.PI * 2);
context.fillStyle = color;
context.fill();
context.closePath();
}
function clearCanvas() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
canvas.addEventListener("mousedown", startPainting);
canvas.addEventListener("mouseup", stopPainting);
canvas.addEventListener("mousemove", draw);
在 JavaScript 中,我们获取了 canvas 元素和用于绘制的上下文。我们还定义了一些变量,用于存储当前画笔颜色以及当前是否正在绘制。
setColor 函数用于设置画笔颜色,它会在点击颜色按钮时调用。startPainting 和 stopPainting 函数用于开启和关闭绘制,它们会在鼠标按下和松开时调用。draw 函数用于实际的绘制操作,它会在鼠标移动时调用。clearCanvas 函数用于清空画布,它会在点击清除画布按钮时调用。
最后,我们为 canvas 元素的 mousedown、mouseup 和 mousemove 事件添加了监听器,用于开始绘制、停止绘制和实际绘制的操作。