Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

ทำให้ canvas เคลื่อนไหวแบบอนันต์เพื่อให้ noise ดูเหมือนเคลื่อนที่ใน HTML


เมธอด putImageData() วางข้อมูลภาพลงบน canvas เพื่อทำให้ canvas เคลื่อนไหว เราสร้าง ImageData object ที่ใช้ซ้ำได้นอกจาก main loop:

var ct = c.getContext("2d", {alpha: false}); // context without alpha channel
var a = ct.createImageData(c.width, c.height);
var buffer = new Uint32Array(a.data.buffer);
function loop() {
  noise(ct);
  requestAnimationFrame(loop)
})()
function noise(ct) {
  var l = buffer.length - 1;
  while(l--) buffer[l] = Math.random() < 0.5 ? 0 : -1 >>> 0;
  ct.putImageData(a, 0, 0);
}