canvas示例系列:
- html:canvas画布绘图简单入门-1
- html:canvas画布绘图简单入门-2
- html:canvas画布绘图简单入门-绘制时钟-3
- html:canvas画布绘图简单入门-刮刮乐-4
内容分辨率: 600 * 700 元素尺寸: 800 * 900
示例6:将元素截取后返回画布像素操作 getImageData() createImageData() putImageData()
let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 50, 50);
let imageData = ctx.getImageData(0, 0, 50, 50);
console.log(imageData);
// 转换元素的颜色数组 RGBA [红色, 绿色, 蓝色, alpha通道]
// [255, 0, 0, 255] => [0, 255, 255, 255]
for (let i = 0; i
let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 50, 50);
// 移动原点坐标(0, 0) => (100, 0)
ctx.translate(100, 0);
ctx.fillStyle = "green";
ctx.fillRect(0, 0, 50, 50);
示例8:旋转坐标轴
let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
// 将坐标轴顺时针旋转45角
ctx.rotate(Math.PI / 180 * 45);
ctx.fillStyle = "red";
ctx.fillRect(25, -25, 50, 50);
示例9:缩放坐标轴
let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 50, 50);
// 保存画笔状态
ctx.save()
// 坐标轴x, y都放大两倍
ctx.scale(2, 2);
ctx.fillStyle = "green";
ctx.fillRect(50, 0, 50, 50);
// 恢复画笔状态
ctx.restore()
ctx.fillRect(250, 0, 50, 50);