欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

canvas动画效果新年祝福话语

程序员文章站 2023-02-20 23:08:05
html代码 css代码 js代码 效果图 ......

html代码

 <ul id="ul"></ul>

css代码

* {
      margin: 0;
      padding: 0;
    }
    ul {
      list-style: none;
      position: relative;
    }
    ul.slow li {
      transition: 2.4s all;
    }
    li {
      width: var(--rect-width);
      height: var(--rect-width);
      position: absolute;
      transition: 2s all;
      left: 0;
      top: 0;
      background: black;
      opacity: 0;
      transform: translate(500px, 100px);
    }

js代码

"use strict";
const rectwidth = parsefloat(document.documentelement.style.getpropertyvalue('--rect-width'));
const canvas = document.createelement('canvas');
canvas.width = 100;
canvas.height = 20;

const ctx = canvas.getcontext('2d');
ctx.font = '100 18px monospace';
ctx.textbaseline = 'top';
ctx.textalign = 'center';
const ul = document.getelementbyid('ul');

function drawtext(text) {
  ctx.clearrect(0, 0, canvas.width, canvas.height);
  const gradient = ctx.createlineargradient(10, 0, canvas.width - 10, 0);
  gradient.addcolorstop(0, 'red');
  gradient.addcolorstop(1 / 6, 'orange');
  gradient.addcolorstop(2 / 6, 'yellow');
  gradient.addcolorstop(3 / 6, 'green');
  gradient.addcolorstop(4 / 6, 'blue');
  gradient.addcolorstop(5 / 6, 'indigo');
  gradient.addcolorstop(1, 'violet');
  ctx.fillstyle = gradient;
  ctx.filltext(text, canvas.width / 2, 2);
  const imagedata = ctx.getimagedata(0, 0, canvas.width, canvas.height);
  let ili = 0;
  for (let column = 0; column < imagedata.width; column++) {
    for (let row = 0; row < imagedata.height; row++) {
      const idx = ((row * imagedata.width) + column) * 4;
      if (imagedata.data[idx + 3] > 0) {
        const li = ul.children[ili++];
        li.style.opacity = '1';
        li.style.transform = `translate(
          ${column * rectwidth}px,
          ${row * rectwidth}px)
          scale(1.5)`;
        li.style.background =
          `rgba(${imagedata.data[idx]},${imagedata.data[idx + 1]},${imagedata.data[idx + 2]},${imagedata.data[idx + 3] / 255})`;
      }
    }
  }
  while (ili < 2000) {
    const li = ul.children[ili++];
    li.style.opacity = '0';
  }
}

const timeout = t => new promise(resolve => settimeout(resolve, t));

void async function main() {
  const duration = 2500;
  {
    let i = 2000;
    const fragment = document.createdocumentfragment();
    while (i-- > 0) {
      fragment.appendchild(document.createelement('li'));
    }
    ul.appendchild(fragment);
  }

  await timeout(100);

  drawtext('新年愿望');
  await timeout(duration);

  drawtext('身体健康');
  await timeout(duration);

  drawtext('有很多钱');
  await timeout(duration);

  ul.classlist.add('slow');
  drawtext('新年快乐!');
}();

效果图

canvas动画效果新年祝福话语