1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 canvas{ 8 border: solid; 9 } 10 </style> 11 </head> 12 <body> 13 <canvas id="canvas" width="400" height="300"></canvas> 14 <script src="main.js"></script> 15 </body> 16 </html>
1 (function () { 2 3 var curX = -400, speed = 1; 4 var text = "Hello World"; 5 var canvas = document.getElementById("canvas"); 6 var con = canvas.getContext("2d"); 7 8 function clearCanvas() { 9 con.clearRect(0, 0, 400, 300); 10 } 11 12 function render() { 13 clearCanvas(); 14 15 con.save(); 16 con.font = "50px 宋体"; 17 con.fillStyle = "#abcdef"; 18 con.fillText(text, 80, 250); 19 con.restore(); 20 21 con.save(); 22 con.beginPath(); 23 curX += speed; 24 con.rect(curX, 0, 400, 300); 25 con.closePath(); 26 con.clip(); 27 28 con.font = "50px 宋体"; 29 con.fillStyle = "coral"; 30 con.fillText(text, 80, 250); 31 con.restore(); 32 // console.log("e"); 33 requestAnimationFrame(render); 34 } 35 36 function init() { 37 render(); 38 } 39 40 init(); 41 })();