<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="Generator" content="EditPlus®"> <meta name="Author" content=""> <meta name= ...
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="Generator" content="EditPlus®"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <title>Document</title> <style> *{ margin:0; padding:0; } /* #canvas{ display:block; border:1px solid blue; margin:100px auto 0; } */ #canvas{ display:block; } </style> </head> <body> <canvas id="canvas"></canvas> <script> var canV = document.getElementById("canvas"), ctX = canV.getContext("2d"); // 1 需要獲取整個可視區域的寬高 賦值給canvas畫布 // 2 準備26個字母 或者是數字 // 3 設置文字的大小 // 4 一行顯示多少個文字 可視區域的寬除以文字的大小 // 5 用數組去記錄我們的y坐標 // [0,0,0,0] [1,1,1,1] [2,2,2,2] 不斷改變數字的大小 字母的y坐標就不斷改變 // 6 需要一個函數去生成字母 var oWidth,oHeight function init(){ oWidth = window.innerWidth // 1 需要獲取整個可視區域的寬高 賦值給canvas畫布 oHeight = window.innerHeight canV.width = oWidth canV.height = oHeight draw() } init() window.onresize = init;
var oText = "QWERTYUIOPASDFGHJKLZXCVBNM", // 2 準備26個字母 oFs = 24 , // 放字體的區域的寬度 oNum = Math.floor(oWidth/oFs), // 4 一行顯示多少個文字 可視區域的寬除以文字的大小 oArry = [] ;
for(var i=0; i<oNum ; i++){ //讓y坐標初始都是0 [0,0,0,0,0...] oArry.push(0) } // 6 需要一個函數去生成字母 function draw(){ ctX.fillStyle = "rgba(0,0,0,0.1)" ctX.fillRect(0,0,oWidth,oHeight) ctX.fillStyle = "green" //ctX.font = oFs + "px" //畫布設置字體的大小 ctX.font = `18px arial`; //1 知道字母的x坐標跟y坐標 //2 隨機生成字母 //3 開始去渲染字母 for(var i=0; i<oNum; i++){ var oX = i*oFs, //X坐標 oY = oArry[i]*oFs, //Y坐標 oRandom = Math.floor(Math.random()*oText.length) ;//隨機一個0-25的數字 ctX.fillText(oText[oRandom],oX,oY) //渲染字母 if( oY > oHeight && Math.random() > 0.95){ oArry[i] = 0 } oArry[i]++ } } setInterval(draw,50) // 每隔50毫秒就執行一次 draw函數 </script> </body> </html> <!-- ctX.moveTo(100,100) ctX.lineTo(200,200) ctX.lineTo(200,100) ctX.lineTo(100,100) //ctX.stroke() ctX.fillStyle ="green" ctX.fill() -->