当前位置:首页 > Python > 正文

Python Canvas画布教程:HTML5画布基础与绘图实战 | 前端开发指南

Python Canvas画布教程

掌握HTML5 Canvas基础,实现图形绘制、动画制作和交互设计

Canvas是什么?

Canvas是HTML5引入的一个强大的绘图API,它允许开发者通过JavaScript在网页上动态绘制图形、创建动画和实现交互效果。

虽然名称中包含"Python",但在Web开发中Canvas通常与JavaScript配合使用。Python开发者可以通过后端生成数据或使用PyScript等工具与Canvas交互。

Canvas核心优势

  • 高性能的2D图形渲染
  • 支持实时动画和游戏开发
  • 无需插件,所有现代浏览器都支持
  • 可以导出为图片或视频

Canvas应用场景

  • 数据可视化图表
  • 网页游戏开发
  • 图像处理和滤镜
  • 交互式教学工具
  • 创意艺术展示

Canvas基础教程

1. 创建Canvas画布

在HTML中添加canvas元素,并设置宽度和高度:

<canvas id="myCanvas" width="600" height="400">
    您的浏览器不支持Canvas,请升级浏览器!
</canvas>

2. 获取绘图上下文

通过JavaScript获取2D绘图上下文:

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

3. 基本绘图方法

绘制矩形

// 填充矩形
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 100, 80);

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

绘制圆形

ctx.beginPath();
ctx.arc(150, 200, 50, 0, Math.PI * 2);
ctx.fillStyle = 'green';
ctx.fill();

ctx.beginPath();
ctx.arc(300, 200, 50, 0, Math.PI * 2);
ctx.strokeStyle = 'purple';
ctx.lineWidth = 4;
ctx.stroke();

绘制文本

ctx.font = 'bold 24px Arial';
ctx.fillStyle = 'darkorange';
ctx.textAlign = 'center';
ctx.fillText('你好,Canvas!', 300, 350);

Canvas动画实战

弹跳球动画

使用Canvas创建简单的弹跳球动画:

const canvas = document.getElementById('animationCanvas');
const ctx = canvas.getContext('2d');

let x = 100;
let y = 100;
let dx = 2;
let dy = 3;
const radius = 30;

function drawBall() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    ctx.beginPath();
    ctx.arc(x, y, radius, 0, Math.PI * 2);
    ctx.fillStyle = 'tomato';
    ctx.fill();
    ctx.closePath();
    
    // 边界检测
    if (x + dx > canvas.width - radius || x + dx < radius) dx = -dx;
    if (y + dy > canvas.height - radius || y + dy < radius) dy = -dy;
    
    x += dx;
    y += dy;
    
    requestAnimationFrame(drawBall);
}

drawBall();

实时Canvas动画演示

完整Canvas绘图板示例

交互式绘图板

创建一个简单的绘图板,允许用户用鼠标在画布上绘图:

const canvas = document.getElementById('drawingCanvas');
const ctx = canvas.getContext('2d');

let isDrawing = false;
let lastX = 0;
let lastY = 0;
let hue = 0;
let lineWidth = 5;

canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mouseout', stopDrawing);

function startDrawing(e) {
    isDrawing = true;
    [lastX, lastY] = [e.offsetX, e.offsetY];
}

function draw(e) {
    if (!isDrawing) return;
    
    ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;
    ctx.lineJoin = 'round';
    ctx.lineCap = 'round';
    ctx.lineWidth = lineWidth;
    
    ctx.beginPath();
    ctx.moveTo(lastX, lastY);
    ctx.lineTo(e.offsetX, e.offsetY);
    ctx.stroke();
    
    [lastX, lastY] = [e.offsetX, e.offsetY];
    
    hue = (hue + 1) % 360;
    if (ctx.lineWidth < 50) lineWidth += 0.05;
}

function stopDrawing() {
    isDrawing = false;
    lineWidth = 5;
}

在画布上拖动鼠标进行绘图

© 2023 Python Canvas教程 | 前端开发学习资源

发表评论