canvas基础

8/27/2018jsAPIhtml5canvas

#概述——什么是 Canvas

canvas 这个元素负责在页面中设定一个区域,然后通过 JS 动态的在这个区域中绘制图形。

#语法

#基本介绍

一般前两个都是要画元素的开始坐标,后两个一般是要画元素本身的配置

#strokeRect()

绘制一个无填充矩形

ctx.strokeRect(20, 20, 150, 100);
// 等同于
ctx.rect(20, 20, 150, 100);
ctx.stroke();
1
2
3
4

#fillRect()

绘制一个填充矩形

ctx.fillRect(20, 20, 150, 100);
// 等同于
ctx.rect(20, 20, 150, 100);
ctx.fill();
1
2
3
4

#beginPath()

起始一条路径或者重置当前路径

ctx.beginPath();
1

#translate();

改变画布的(0, 0)点也就是原点

ctx.translate(20, 30);
1

#moveTo()和 lineTo()

前一个是把路径移动到指定点,后一个是添加一个新点,两者往往一起使用

ctx.moveTo(10, 10);
ctx.lineTo(50, 50);
1
2

#arc()

画圆的基本语法

// 最后一个参数为可选参数,默认false为逆时针
ctx.arc(100, 75, 50, 0, 2 * Math.PI, false);
1
2

#rotate()

旋转的基本语法

ctx.rotate((20 * Math.PI) / 180);
1

#clearRect()

清除画布的基本语法

ctx.clearRect(20, 20, 100, 50);
1

#canvas 的使用

#在 html 页面插入 canvas

<canvas id="content" width="200" height="200"></canvas>
1

#插入一张图片

const content = document.querySelector("#content");
let ctx = content.getContext("2d");
let image = new Image();
image.onload = function() {
  ctx.drawImage(image, 0, 0, content.width, content.height);
  // 加入文字渲染
  ctx.font = "36pt Impact";
  ctx.textAlign = "center";
  ctx.fillStyle = "#fff";
  ctx.fillText("This is a pug", content.width / 2, 50);
  ctx.strokeStyle = "#000";
  ctx.lineWidth = 3;
  ctx.strokeText("This is a pug", content.width / 2, 50);
};

image.src =
  "https://upload.wikimedia.org/wikipedia/commons/f/f3/Mops-duke-mopszucht-vom-maegdebrunnen.jpg";
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

效果图

#绘制一个时钟

时钟源代码(opens new window)

#参考教程

Last Updated:5/25/2024, 2:23:06 AM