学习如何使用Canvas绘制图形和动画
Canvas是HTML5提供的一个绘图元素,可以通过JavaScript进行图形绘制:
<canvas id="myCanvas" width="300" height="200">
您的浏览器不支持Canvas
</canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
</script>
Canvas支持多种基本图形的绘制:
// 绘制矩形
ctx.fillStyle = '#e8491d';
ctx.fillRect(50, 50, 100, 50);
// 绘制边框
ctx.strokeStyle = '#35424a';
ctx.strokeRect(50, 50, 100, 50);
// 绘制圆形
ctx.beginPath();
ctx.arc(100, 75, 40, 0, Math.PI * 2);
ctx.fillStyle = '#e8491d';
ctx.fill();
ctx.stroke();
// 绘制线条
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 100);
ctx.strokeStyle = '#e8491d';
ctx.lineWidth = 2;
ctx.stroke();
Canvas可以绘制文本,支持多种字体和样式:
// 设置文本样式
ctx.font = '30px Arial';
ctx.fillStyle = '#e8491d';
ctx.textAlign = 'center';
ctx.fillText('Hello Canvas!', 200, 100);
// 绘制描边文本
ctx.strokeStyle = '#35424a';
ctx.strokeText('Hello Canvas!', 200, 150);
Canvas可以加载和处理图像:
// 加载图像
const img = new Image();
img.src = 'image.jpg';
img.onload = function() {
// 绘制图像
ctx.drawImage(img, 0, 0, 400, 300);
// 添加滤镜效果
const imageData = ctx.getImageData(0, 0, 400, 300);
const data = imageData.data;
for (let i = 0; i < data.length; i += 4) {
data[i] = data[i] * 1.2; // 红色
data[i + 1] = data[i + 1]; // 绿色
data[i + 2] = data[i + 2]; // 蓝色
}
ctx.putImageData(imageData, 0, 0);
};
使用requestAnimationFrame创建动画:
let animationId;
let x = 0;
function animate() {
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制移动的圆形
ctx.beginPath();
ctx.arc(x, 150, 20, 0, Math.PI * 2);
ctx.fillStyle = '#e8491d';
ctx.fill();
// 更新位置
x += 2;
if (x > canvas.width) x = 0;
// 继续动画
animationId = requestAnimationFrame(animate);
}
function startAnimation() {
animate();
}
function stopAnimation() {
cancelAnimationFrame(animationId);
}
Canvas可以响应用户交互:
// 监听鼠标移动
canvas.addEventListener('mousemove', function(e) {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制跟随鼠标的圆形
ctx.beginPath();
ctx.arc(x, y, 20, 0, Math.PI * 2);
ctx.fillStyle = '#e8491d';
ctx.fill();
});