Canvas 应用示例<1>

Canvas 基础应用示例

Canvas 是 HTML5 提供的绘图 API,可以在网页上绘制图形、动画、游戏等。下面是一些基础示例帮助你学习 Canvas 的使用。

1. 基本 Canvas 设置

首先需要在 HTML 中创建 canvas 元素:

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>Canvas 基础示例</title>
    <style>
        canvas {
            border: 1px solid black;
            background-color: #f0f0f0;
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="500" height="300"></canvas>
    <script src="script.js"></script>
</body>
</html>

2. 获取 Canvas 上下文

在 JavaScript 中获取 Canvas 的绘图上下文:

javascript 复制代码
// script.js
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

3. 绘制基本形状

绘制矩形

javascript 复制代码
// 填充矩形
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 80);

// 描边矩形
ctx.strokeStyle = 'blue';
ctx.lineWidth = 3;
ctx.strokeRect(200, 50, 100, 80);

绘制圆形

javascript 复制代码
ctx.beginPath();
ctx.arc(150, 200, 50, 0, Math.PI * 2); // x, y, 半径, 起始角, 结束角
ctx.fillStyle = 'green';
ctx.fill();
ctx.strokeStyle = 'black';
ctx.stroke();

绘制线条

javascript 复制代码
ctx.beginPath();
ctx.moveTo(300, 150); // 起点
ctx.lineTo(400, 250); // 终点
ctx.lineTo(350, 300); // 另一个点
ctx.closePath();      // 闭合路径
ctx.strokeStyle = 'purple';
ctx.lineWidth = 5;
ctx.stroke();

4. 绘制文本

javascript 复制代码
ctx.font = '30px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello Canvas!', 50, 100);

ctx.font = '20px Arial';
ctx.strokeStyle = 'blue';
ctx.strokeText('描边文本', 50, 150);

5. 绘制图像

javascript 复制代码
const img = new Image();
img.src = 'path/to/image.jpg';
img.onload = function() {
    // 绘制完整图像
    ctx.drawImage(img, 300, 100);
    
    // 绘制部分图像
    // ctx.drawImage(img, sourceX, sourceY, sourceWidth, sourceHeight, 
    //               destX, destY, destWidth, destHeight);
};

6. 动画示例 - 移动的小球

javascript 复制代码
let x = 50;
let y = 150;
let dx = 2;
let radius = 30;

function drawBall() {
    ctx.beginPath();
    ctx.arc(x, y, radius, 0, Math.PI * 2);
    ctx.fillStyle = 'orange';
    ctx.fill();
    ctx.stroke();
}

function animate() {
    // 清除画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 绘制小球
    drawBall();
    
    // 更新位置
    x += dx;
    
    // 边界检测
    if (x + radius > canvas.width || x - radius < 0) {
        dx = -dx;
    }
    
    // 循环动画
    requestAnimationFrame(animate);
}

animate();

7. 交互示例 - 跟随鼠标的图形

javascript 复制代码
canvas.addEventListener('mousemove', function(event) {
    // 获取鼠标位置
    const rect = canvas.getBoundingClientRect();
    const mouseX = event.clientX - rect.left;
    const mouseY = event.clientY - rect.top;
    
    // 清除画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 绘制跟随鼠标的图形
    ctx.beginPath();
    ctx.arc(mouseX, mouseY, 40, 0, Math.PI * 2);
    ctx.fillStyle = 'rgba(0, 100, 255, 0.7)';
    ctx.fill();
});

8. 渐变和阴影

javascript 复制代码
// 线性渐变
const gradient = ctx.createLinearGradient(50, 50, 250, 50);
gradient.addColorStop(0, 'red');
gradient.addColorStop(0.5, 'yellow');
gradient.addColorStop(1, 'green');

ctx.fillStyle = gradient;
ctx.fillRect(50, 50, 200, 100);

// 径向渐变
const radialGradient = ctx.createRadialGradient(350, 150, 10, 350, 150, 50);
radialGradient.addColorStop(0, 'white');
radialGradient.addColorStop(1, 'blue');

ctx.fillStyle = radialGradient;
ctx.fillRect(300, 100, 100, 100);

// 阴影
ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
ctx.shadowBlur = 10;
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;

ctx.fillStyle = 'purple';
ctx.fillRect(50, 200, 100, 80);

// 重置阴影
ctx.shadowColor = 'transparent';

这些基础示例涵盖了 Canvas 的主要功能,你可以基于这些示例进行扩展,创建更复杂的图形和动画效果。

相关推荐
子兮曰3 天前
深入 HTML-in-Canvas:当 Canvas 学会了渲染 DOM,前端图形生态要变天了
前端·javascript·canvas
七夜zippoe5 天前
OpenClaw Canvas 可视化界面详解
可视化·canvas·flexbox·ai agent·openclaw
ncj3934379068 天前
Canvas 图形开发高频算法面试题
算法·canvas
pancakenut10 天前
从盒模型到画布:以mapbox为例
前端·canvas
ouzz18 天前
我在 React Canvas 里做了一个液态玻璃透镜效果
canvas·视觉设计
ouzz19 天前
使用纯canvas绘制一个掘金首页
前端·canvas
roamingcode20 天前
支付宝小程序数据可视化避坑指南:@antv/f2 踩坑与最佳实践
信息可视化·小程序·canvas·antv
可夫小子21 天前
不用 Tailscale:3 步把 Mac mini 通过 FRP 暴露到公网(稳定开机自启)
canvas
叫我一声阿雷吧25 天前
原生 JS 实现图片预览上传组件:多图上传 + 拖拽上传 + 裁剪预览 + 进度显示(附完整源码)
图片上传·canvas·文件上传·响应式布局·拖拽上传·原生javascript·filereader api
天若有情6731 个月前
Canvas生成艺术|意外诞生的混沌风暴(附完整源码+GitHub部署)
前端·css·html·github·canvas·网页