Как сделать canvas задним фоном на сайте? Без дополнительных библиотек и т.п?

Пытался через z-index: -1; - для canvas. И position absolute для остальных элементов страницы, но что-то не то.


Ответы (2 шт):

Автор решения: CbIPoK2513

let cnv = document.querySelector("#bg");
let ctx = cnv.getContext('2d');

// Высота холста и элемента будет равна размеру экрана соответственно.
let WID = cnv.width = window.innerWidth;
let HEI = cnv.height = window.innerHeight; 

const LIMIT = 200;
let points = [];
let size = 2;

// Так же понадобиться слушатель на изменение размера окна, который так же будет менять значения
window.addEventListener('resize', function(){
    WID = cnv.width = window.innerWidth;
  HEI = cnv.height = window.innerHeight;
}, false);

(function draw() {
  ctx.clearRect(0, 0, WID, HEI);
  points.forEach(function (point) {
    ctx.fillStyle = point.color;
    ctx.fillRect(point.x, point.y, size, size);
  });

  points.push( new Point() );
  if (points.length > LIMIT) points.shift();

  requestAnimationFrame(draw);
})();

function rand_color() {
  let r = Math.random() * 256 | 0;
  let g = Math.random() * 256 | 0;
  let b = Math.random() * 256 | 0;
  
  return `rgb(${ r },${ g },${ b })`;
}

function Point() {
  this.x = Math.random() * (WID - size) | 0;
  this.y = Math.random() * (HEI - size) | 0;
  this.color = rand_color();
}
body {
  margin: 0;
}

#bg {
  display: block;
  width: 100%;
  height: 100%;
  background: transparent;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1;
}

main {
  display: block;
  width: 100%;
  max-width: 400px;
  min-height: 100vh;
  margin: 0 auto;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  z-index: 2;
  padding: 10px;
  box-sizing: border-box;
}

.gallery {
  display: grid;
  grid-template-areas:
    'A A C'
    'B B C'
    'D D D';
  grid-gap: 2vw;
  width: 100%;
  
}

.gallery img {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.gallery img:nth-child(1) {
  grid-area: A;
}

.gallery img:nth-child(2) {
  grid-area: D;
}

.gallery img:nth-child(3) {
  grid-area: B;
}

.gallery img:nth-child(4) {
  grid-area: C;
}
<canvas id="bg"></canvas>
<main>
  <h1>Котята</h1>
  <div class="gallery">
    <img src="//i.imgur.com/VQ0MFSW.png">
    <img src="//i.imgur.com/kFbk7Ir.jpg">
    <img src="//i.imgur.com/MrGJ8pU.jpg">
    <img src="//i.imgur.com/ix1WHwD.jpg">
  </div>
</main>

→ Ссылка
Автор решения: DiD

let canvas = document.getElementById('game');
let ctx, pixels, [w,h] = [212 * 2,120 * 2],
    [map,texmap] = [new Array(64 * 64 * 64),new Array(16 * 16 * 3 * 16)];

function init() {
  for (let i = 1; i < 16; i++) {
    let br = 255 - ((Math.random() * 96) | 0);
    for (let y = 0; y < 16 * 3; y++) {
      for (let x = 0; x < 16; x++) {
        let color = 0x966C4A;
        if (i == 4)
          color = 0x7F7F7F;
        if (i != 4 || ((Math.random() * 3) | 0) == 0) {
          br = 255 - ((Math.random() * 96) | 0);
        }
        if ((i == 1 && y < (((x * x * 3 + x * 81) >> 2) & 3) + 18)) {
          color = 0x6AAA40;
        } else if ((i == 1 && y < (((x * x * 3 + x * 81) >> 2) & 3) + 19)) {
          br = br * 2 / 3;
        }
        if (i == 7) {
          color = 0x675231;
          if (x > 0 && x < 15 &&
            ((y > 0 && y < 15) || (y > 32 && y < 47))) {
            color = 0xBC9862;
            let [xd,yd] = [x - 7,(y & 15) - 7];
            if (xd < 0)
              xd = 1 - xd;
            if (yd < 0)
              yd = 1 - yd;
            if (yd > xd)
              xd = yd;

            br = 196 - ((Math.random() * 32) | 0) + xd % 3 * 32;
          } else if (((Math.random() * 2) | 0) == 0) {
            br = br * (150 - (x & 1) * 100) / 100;
          }
        }

        if (i == 5) {
          color = 0xB53A15;
          if ((x + (y >> 2) * 4) % 8 == 0 || y % 4 == 0) {
            color = 0xBCAFA5;
          }
        }
        if (i == 9) {
          color = 0x4040ff;
        }
        let brr = br;
        if (y >= 32)
          brr /= 2;

        if (i == 8) {
          color = 0x50D937;
          if (((Math.random() * 2) | 0) == 0) {
            color = 0;
            brr = 255;
          }
        }

        let col = (((color >> 16) & 0xff) * brr / 255) << 16 |
          (((color >> 8) & 0xff) * brr / 255) << 8 |
          (((color) & 0xff) * brr / 255);
        texmap[x + y * 16 + i * 256 * 3] = col;
      }
    }
  }

  ctx = canvas.getContext('2d');

  for (let x = 0; x < 64; x++) {
    for (let y = 0; y < 64; y++) {
      for (let z = 0; z < 64; z++) {
        let i = z << 12 | y << 6 | x;
        let [yd,zd] = [(y - 32.5) * 0.4,(z - 32.5) * 0.4];
        map[i] = (Math.random() * 16) | 0;
        if (Math.random() > Math.sqrt(Math.sqrt(yd * yd + zd * zd)) - .8)
          map[i] = 0;
      }
    }
  }

  pixels = ctx.createImageData(w, h);

  for (let i = 0; i < w * h; i++) {
    pixels.data[i * 4 + 3] = 255;
  }

  setInterval(clock, 1000 / 100);
};

function clock() {
  renderMinecraft();
  ctx.putImageData(pixels, 0, 0);
};

let f = 0;

function renderMinecraft() {
  let [xRot,yRot] = [ Math.sin(Date.now() % 10000 / 10000 * Math.PI * 2) * .4 + Math.PI / 2, 
                      Math.cos(Date.now() % 10000 / 10000 * Math.PI * 2) * .4],
      [yCos,ySin,xCos,xSin] = [ Math.cos(yRot), Math.sin(yRot), Math.cos(xRot), Math.sin(xRot)],
      [ox,oy,oz] = [ 32.5 + Date.now() % 10000 / 10000 * 64, 32.5, 32.5];

  f++;
  for (let x = 0; x < w; x++) {
    let ___xd = (x - w / 2) / h;
    for (let y = 0; y < h; y++) {
      let [__yd,__zd] = [(y - h / 2) / h, 1],
          [ ___zd,_yd] = [__zd * yCos + __yd * ySin, __yd * yCos - __zd * ySin],
          [_xd,_zd] = [___xd * xCos + ___zd * xSin,___zd * xCos - ___xd * xSin];

      let [col,br,ddist,closest] = [0,255, 0,32];
      for (let d = 0; d < 3; d++) {
        let dimLength = _xd;
        if (d == 1)
          dimLength = _yd;
        if (d == 2)
          dimLength = _zd;

        let ll = 1 / (dimLength < 0 ? -dimLength : dimLength),
            [xd,yd,zd] = [_xd * ll,_yd * ll, _zd * ll],
            initial = ox - (ox | 0);

        if (d == 1)
          initial = oy - (oy | 0);
        if (d == 2)
          initial = oz - (oz | 0);
        if (dimLength > 0)
          initial = 1 - initial;

        let dist = ll * initial;

        let [xp,yp,zp] = [ox + xd * initial, oy + yd * initial,oz + zd * initial];

        if (dimLength < 0) {
          if (d == 0)
            xp--;
          if (d == 1)
            yp--;
          if (d == 2)
            zp--;
        }

        while (dist < closest) {
          let tex = map[(zp & 63) << 12 | (yp & 63) << 6 | (xp & 63)];

          if (tex > 0) {
            let [u,v] = [((xp + zp) * 16) & 15, ((yp * 16) & 15) + 16];
            if (d == 1) {
              [u,v] = [(xp * 16) & 15, ((zp * 16) & 15)];
              if (yd < 0) v += 32;
            }

            let cc = texmap[u + v * 16 + tex * 256 * 3];
            if (cc > 0) {
              [col,ddist,br,closest] = [cc,
                                        255 - ((dist / 32 * 255) | 0),
                                        255 * (255 - ((d + 2) % 3) * 50) / 255,
                                        dist];
            }
          }
          xp += xd;
          yp += yd;
          zp += zd;
          dist += ll;
        }
      }

      let [r,g,b] = [((col >> 16) & 0xff) * br * ddist / (255 * 255),
                     ((col >> 8) & 0xff) * br * ddist / (255 * 255),
                     ((col) & 0xff) * br * ddist / (255 * 255)]; 

      pixels.data[(x + y * w) * 4 + 0] = r;
      pixels.data[(x + y * w) * 4 + 1] = g;
      pixels.data[(x + y * w) * 4 + 2] = b;
    }
  }
}

init();
body{margin:0;}

canvas {
  image-rendering: optimizeSpeed;
  image-rendering: -moz-crisp-edges;
  image-rendering: -webkit-optimize-contrast;
  image-rendering: optimize-contrast;
  -ms-interpolation-mode: nearest-neighbor;
  width: 848px;
  height: 480px;
  top: 0;
  left:0;
  position:absolute;
  z-index: -1;
}

div {
  width: 424px;
  height: 240px;
  left: 212px;
  top: 120px;
  background: #fff4;
  z-index: 10;
  position: absolute;
  font-size: 4rem;
  color: #fff;
  text-align: center;
  line-height: calc(120px + 6rem);
  text-shadow: -2px  2px 3px #000,
                2px -2px 3px #000,
               -2px -2px 3px #000,
                2px  2px 3px #000;
  backdrop-filter: blur(10px);
}
<canvas id="game" width="424" height="240"></canvas>
<div>Hello, world!</div>

→ Ссылка