HTMLcanvas矩形阵雨 - 学习笔记

HTMLcanvas矩形阵雨

  • 在画布上执行
  • 获取制图环境
  • 全屏获取屏幕宽度和屏幕高度
  • 确定每个文字的宽度 以确定列
  • 循环输出
  • 定时器调用

HTML 部分

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>HTMLcanvas矩形阵雨</title>
</head>
<body>
<canvas id="c">您的浏览器不支持 请升级</canvas>
</body>
</html>

CSS 部分

<style type="text/css">
/* 基本的复位 */
* {
    margin:0;
    padding:0;
}
/* 给body一个背景 使画布看起来更清晰 */
body {
    background-color:#000;
}
canvas {
    display:block;
}
</style>

Javascript 部分

<script type="text/jscript">
 var c = document.getElementById("c"); //获取id
 var ctx = c.getContext("2d"); //2d制图
 
 c.width = window.innerWidth; //获取屏幕宽度
 c.height = window.innerHeight; //获取屏幕高度
 
 var chinese = "abcdefghijklmnopqrstuvwxyz"; //canvas 阵雨文字
 chinese = chinese.split(""); //split 分离
 
 var font_size = 10; //字体大小 10px
 var columns = c.width/font_size; 
 //获取列 屏幕宽度/字体大小
 var drops = []; // drop 落下 新建数组
 for(n=0; n < columns; n++) //控制列输出
     drops[n] = 1;
 //draw
 function draw(){
     ctx.fillStyle = "rgba(0,0,0,0.05)"; //绘制矩形
     ctx.fillRect(0,0,c.width,c.height); //以(0,0)为坐标 画制矩形
     
     ctx.fillStyle = "#0F0"; //绿色字体
     ctx.font = font_size + "px arial"; //以像素为单位 宋体
          
     for(var i=0; i< drops.length; i++)
     {
         var text = chinese[Math.floor(Math.random()*chinese.length)];
         // Math.floor 对浮点数向下取整
         ctx.fillText(text, i*font_size, drops[i]*font_size);
         // 规定在画布上输出的文本 开始绘制文本的x坐标 y坐标
         if(drops[i]*font_size > c.height && Math.random() > 0.975)
         // 如果下落的文本大于屏幕高度 或者 随机数大于0.975
             drops[i] = 0;
         // 重置下落
         drops[i]++;
         // 继续执行
     }
 }
 setInterval(draw,33); //33 执行一次draw()
</script>

此文到此结束

 

 

我始终相信这个世界上充满了美好与希望 加油!

 

posted @ 2017-05-26 00:34  唯爱小面包  阅读(371)  评论(0编辑  收藏  举报