Make Some Noise

Generate noise textures at runtime.

by Ian McKellar

HTML

<div class="noise">

</div>
<h1>Hello, noise</h1>

CSS

body {
  padding: 0;
  margin: 0;
  background-color: green;
  color: white;
  font-family: sans-serif;
}
.noise {
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  opacity: 0.2;
  position: absolute;
  z-index: -1;
}

JavaScript

function makeSomeNoise() {
	const size = 128;
  const canvas = document.createElement("canvas");
  canvas.width = 128;
  canvas.height = 128;
  const ctx = canvas.getContext("2d");
  const data = ctx.getImageData(0, 0, canvas.width, canvas.height);
  window.crypto.getRandomValues(data.data);
  ctx.putImageData(data, 0, 0);

  const style = document.createElement("style");
  style.textContent = `.noise { background-image: url(${canvas.toDataURL("image/png")}); }`;
  document.head.appendChild(style);
}

makeSomeNoise();