JavaScript可以通过表单元素(如输入框、下拉菜单、单选按钮等)来控制HTML5 Canvas的绘制内容。这种交互方式允许用户动态调整画布上的图形、颜色、大小等属性。
requestAnimationFrame
或事件监听来实现实时更新<!DOCTYPE html>
<html>
<head>
<title>Canvas表单控制示例</title>
<style>
body { font-family: Arial, sans-serif; }
.controls { margin-bottom: 20px; }
label { margin-right: 10px; }
</style>
</head>
<body>
<div class="controls">
<label>
形状:
<select id="shape">
<option value="circle">圆形</option>
<option value="square">方形</option>
<option value="triangle">三角形</option>
</select>
</label>
<label>
颜色:
<input type="color" id="color" value="#ff0000">
</label>
<label>
大小:
<input type="range" id="size" min="10" max="200" value="50">
</label>
<label>
旋转角度:
<input type="range" id="rotation" min="0" max="360" value="0">
</label>
</div>
<canvas id="myCanvas" width="500" height="300" style="border:1px solid #000;"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 获取表单元素
const shapeSelect = document.getElementById('shape');
const colorInput = document.getElementById('color');
const sizeInput = document.getElementById('size');
const rotationInput = document.getElementById('rotation');
// 初始绘制
drawCanvas();
// 为所有表单元素添加事件监听
shapeSelect.addEventListener('change', drawCanvas);
colorInput.addEventListener('input', drawCanvas);
sizeInput.addEventListener('input', drawCanvas);
rotationInput.addEventListener('input', drawCanvas);
function drawCanvas() {
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 获取当前表单值
const shape = shapeSelect.value;
const color = colorInput.value;
const size = parseInt(sizeInput.value);
const rotation = parseInt(rotationInput.value) * Math.PI / 180;
// 保存当前状态
ctx.save();
// 移动到画布中心
ctx.translate(canvas.width / 2, canvas.height / 2);
// 应用旋转
ctx.rotate(rotation);
// 设置填充颜色
ctx.fillStyle = color;
// 根据选择的形状绘制
switch(shape) {
case 'circle':
ctx.beginPath();
ctx.arc(0, 0, size / 2, 0, Math.PI * 2);
ctx.fill();
break;
case 'square':
ctx.fillRect(-size / 2, -size / 2, size, size);
break;
case 'triangle':
ctx.beginPath();
ctx.moveTo(0, -size / 2);
ctx.lineTo(size / 2, size / 2);
ctx.lineTo(-size / 2, size / 2);
ctx.closePath();
ctx.fill();
break;
}
// 恢复状态
ctx.restore();
}
</script>
</body>
</html>
clearRect()
,并正确绑定事件监听器requestAnimationFrame
进行优化,或添加防抖函数save()
和restore()
管理绘图状态,或在变换前保存原始坐标parseInt()
或parseFloat()
通过这种方式,可以创建高度交互性的Canvas应用,让用户通过表单控件实时调整画布内容。