fezaoduke / fe-practice-hard

晚练课
69 stars 6 forks source link

第 108 期(W3C标准-canvas):碎屑特效 #111

Open wingmeng opened 5 years ago

wingmeng commented 5 years ago

在 canvas 中,getImageData() 方法可以复制画布上指定矩形的像素数据,putImageData() 方法可以将图像数据放回画布。

示例

<canvas id="myCanvas" width="400" height="260" style="border: 1px solid #ccc"></canvas>
let canvas = document.getElementById('myCanvas');
let ctx = canvas.getContext('2d');
let size = 3;  // 碎屑尺寸
let nums = 200;  // 数量

ctx.fillStyle = `rgb(${rdmNum(255)}, ${rdmNum(255)}, ${rdmNum(255)})`;
ctx.fillRect(10, 10, size, size);

function copy() {
  let imgData = ctx.getImageData(10, 10, size, size);
  ctx.putImageData(imgData, rdmNum(canvas.width - size), rdmNum(canvas.height - size));
}

function rdmNum(max) {
  return (Math.random() * max) >>> 0;
}

for (let i = 0; i < nums; i++) {
  copy();
}