Canvas 是 HTML5 中的一种用于绘制图形的元素,它提供了一种通过 JavaScript 在网页上绘制图形的方式。以下是关于 Canvas 的基础知识和常见用法的总结:
什么是 Canvas?
Canvas 是一个 HTML 元素,允许你通过 JavaScript 绘制图形、图像和动画。它的基本语法如下:
<canvas id="myCanvas" width="500" height="500"></canvas>
2. 获取 Canvas 上下文
在使用 Canvas 绘图之前,你需要获取其上下文(context)。通常使用 2D 上下文来进行绘制:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
3. 绘制基本形状
绘制矩形
// 填充矩形
ctx.fillStyle = 'red'; // 设置填充颜色
ctx.fillRect(20, 20, 150, 100); // x, y, width, height
// 描边矩形
ctx.strokeStyle = 'blue'; // 设置描边颜色
ctx.strokeRect(20, 150, 150, 100); // x, y, width, height
绘制圆形
ctx.beginPath(); // 开始新的路径
ctx.arc(240, 240, 50, 0, Math.PI * 2); // x, y, radius, startAngle, endAngle
ctx.fillStyle = 'green'; // 填充颜色
ctx.fill(); // 填充
ctx.stroke(); // 描边
4. 绘制文本
ctx.font = '30px Arial'; // 设置字体
ctx.fillStyle = 'black'; // 设置文本颜色
ctx.fillText('Hello Canvas', 50, 50); // 文本内容, x, y
5. 绘制图像
const img = new Image(); // 创建新的图像对象
img.src = 'path/to/image.jpg'; // 设置图像源
img.onload = function() {
ctx.drawImage(img, 0, 0, 100, 100); // 绘制图像,x, y, width, height
};
6. 变换 (Transformations)
Canvas 支持变换,如平移、旋转和缩放。
平移
ctx.translate(50, 50); // 平移
ctx.fillRect(20, 20, 150, 100); // 绘制矩形
旋转
ctx.rotate((Math.PI / 180) * 45); // 旋转 45 度
ctx.fillRect(20, 20, 150, 100); // 绘制矩形
缩放
ctx.scale(2, 2); // 在 x 和 y 方向上缩放 2 倍
ctx.fillRect(20, 20, 75, 50); // 绘制矩形
7. 清除画布
可以使用 clearRect 方法清除画布的某个区域:
ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除整个画布
8. 动画
使用 requestAnimationFrame 可以创建动画效果:
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布
ctx.fillRect(x, 50, 50, 50); // 绘制矩形
x += 1; // 更新位置
requestAnimationFrame(animate); // 请求下一帧
}
animate(); // 启动动画
9. 事件处理
可以为 Canvas 添加事件监听器,例如鼠标点击事件:
canvas.addEventListener('click', function(event) {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left; // 获取点击位置的 x 坐标
const y = event.clientY - rect.top; // 获取点击位置的 y 坐标
console.log(Clicked at: (${x}, ${y})
);
});
10. 其他功能
路径:可以使用 beginPath()、moveTo()、lineTo() 等方法绘制复杂的路径。
渐变:使用 createLinearGradient() 和 createRadialGradient() 创建渐变效果。
阴影:可以设置阴影属性,如 shadowColor、shadowBlur、shadowOffsetX 和 shadowOffsetY。
评论区