HTML5系列(4)--Canvas 绘图详解

前端技术探索系列:HTML5 Canvas 绘图详解 🎨

开篇寄语 👋

前端开发者们,

在前四篇文章中,我们探讨了 HTML5 的各种特性。今天,让我们一起探索 Canvas 的神奇世界,看看如何用代码创造出绚丽的视觉效果。

一、Canvas 基础入门 🖌️

1. 创建 Canvas 环境

<canvas id="myCanvas" width="800" height="600">
  您的浏览器不支持 Canvas 元素
</canvas>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// 设置画布尺寸为设备像素比
function setCanvasSize() {
   
  const dpr = window.devicePixelRatio || 1;
  canvas.width = canvas.clientWidth * dpr;
  canvas.height = canvas.clientHeight * dpr;
  ctx.scale(dpr, dpr);
}

2. 基础图形绘制 ⭐

class CanvasDrawing {
   
  constructor(ctx) {
   
    this.ctx = ctx;
  }
  
  // 矩形
  drawRect(x, y, width, height, style = '#000') {
   
    this.ctx.fillStyle = style;
    this.ctx.fillRect(x, y, width, height);
  }
  
  // 圆形
  drawCircle(x, y, radius, style = '#000') {
   
    this.ctx.beginPath();
    this.ctx.arc(x, y, radius, 0, Math.PI * 2);
    this.ctx.fillStyle = style;
    this.ctx.fill();
  }
  
  // 线条
  drawLine(startX, startY, endX, endY, style = '#000', width = 1) {
   
    this.ctx.beginPath();
    this.ctx.moveTo(startX, startY);
    this.ctx.lineTo(endX, endY);
    this.ctx.strokeStyle = style;
    this.ctx.lineWidth = width;
    this.ctx.stroke();
  }
  
  // 文本
  drawText(text, x, y, style = '#000', font = '16px Arial') {
   
    this.ctx.font = font;
    this.ctx.fillStyle = style;
    this.ctx.fillText(text, x, y);
  }
}

3. 路径与形状 ✨

class PathDrawing {
   
  constructor(ctx) {
   
    this.ctx = ctx;
  }
  
  // 绘制多边形
  drawPolygon(points, style = '#000', fill = true) {
   
    this.ctx.beginPath();
    this.ctx.moveTo(points[0].x, points[0].y);
    
    for (let i = 1; i < points.length; i++) {
   
      this.ctx.lineTo(points[i].x, points[i].y);
    }
    
    this.ctx.closePath();
    
    if (fill) {
   
      this.ctx.fillStyle = style;
      this.ctx.fill();
    } else {
   
      this.ctx.strokeStyle = style;
      this.ctx.stroke();
    }
  }
  
  // 贝塞尔曲线
  drawCurve(startX
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值