首页 > 解决方案 > Js,HTML和CSS使矩阵彩虹雨不起作用

问题描述

https://codepen.io/deathshadow8123/pen/KKNaLXq这是我来自codepen的笔,但是当我创建一个html文档并将js放入标签并将css放入标签时,它不会显示在网页上我也把它放在那里。请帮助我,我不知道如何使这项工作。有任何想法吗?如果您无法访问 codepen,这是我的代码:

var w = c.width = window.innerWidth,
    h = c.height = window.innerHeight,
    ctx = c.getContext( '2d' ),
    
    opts = {
      
      chars: '\1234567890ìqwertyuiopè+asdfghjklòàù<zxcvbnm,.-|!"£$%&/()=?^QWERTYUIOPé*ASDFGHJKLç°§>ZXCVBNM;:_[]@#€{}'.split(''), // every key in the italian keyboard layout. It sucks, we don't even have a backtick!
      font: '12px monospace',
      charSize: 14,
      lineHeight: 14,
      
      hueSpeed: 1,
      repaintAlpha: .1,
      
      stripesParXxY: .1,
      stripeSpeed: .5,
      beforeSpawning: 50
    },
    
    tick = 0,
    endX = ( w / opts.charSize + 1 ) |0,
    endY = ( h / opts.lineHeight + 1 ) |0,    
    sum = w + h,
    stripes = [];

ctx.font = opts.font;
ctx.fillStyle = '#111';
ctx.fillRect( 0, 0, w, h );

function loop() {
  
  window.requestAnimationFrame( loop );
  
  tick += opts.hueSpeed;
  
  ctx.fillStyle = 'rgba(0,0,0,alp)'.replace( 'alp', opts.repaintAlpha );
  ctx.fillRect( 0, 0, w, h );
  
  stripes.map( function( stripe ){ stripe.step(); } );
}

function Stripe(){
  
  this.reset();
}
Stripe.prototype.reset = function() {
  
  this.x = ( Math.random() * endX ) |0;
  this.y = -Math.random() * opts.beforeSpawning;
}
Stripe.prototype.step = function() {
  
  this.y += opts.stripeSpeed;
  
  drawLetter( this.x, this.y|0 );
  
  if( this.y > endX )
    this.reset();
}

function drawLetter( x, y ){
  
  x *= opts.charSize;
  y *= opts.lineHeight;
  
  ctx.fillStyle = 'hsl(hue,80%,50%)'.replace( 'hue', ( x + y ) / sum * 360 + tick );
  ctx.fillText( opts.chars[ ( Math.random() * opts.chars.length ) |0 ], x, y );
}

for( var i = 0; i < endX*endX * opts.stripesParXxY; ++i )
  stripes.push( new Stripe );

loop();

window.addEventListener( 'resize', function(){
  
  w = c.width = window.innerWidth;
  h = c.height = window.innerHeight;
  ctx.fillStyle = '#111';
  ctx.fillRect( 0, 0, w, h );
  ctx.font = opts.font;
  
  endX = ( w / opts.charSize + 1 ) |0;
  endY = ( h / opts.lineHeight + 1 ) |0;  
  sum = w + h;
  
  stripes.length = 0;
  for( var i = 0; i < endX*endY * opts.stripesParXxY; ++i )
    stripes.push( new Stripe );
})
canvas {
  
  position: absolute;
  top: 0;
  left: 0;
}
<canvas id=c></canvas>

标签: javascripthtmlcss

解决方案


加载 DOM后,您需要在脚本或加载处理程序函数的顶部获取对画布 DOM 元素的引用。

const c = document.getElementById("c");

最好在你的 html 中使用引号。

例如

<canvas id="c"></canvas>

推荐阅读