|
|

楼主 |
发表于 2022-8-17 19:16
|
显示全部楼层
代码(使用时应根据需要修改相应的东东):
- <style>
- #papa { margin: auto; width: 720px; height: 460px; display:grid; place-items: center; position: relative; }
- #canv { position: absolute; border: 1px solid; }
- </style>
- <div id="papa">
- <canvas id="canv" width="320" height="260"></canvas>
- </div>
- <script>
- let ctx = canv.getContext('2d');
- let w = canv.width, h = canv.height;
- let txtAr = ['荆溪白石出,', '天寒红叶稀。', '山路元无雨,', '空翠湿人衣。'];
- let lineNow = 0, lineHeight = 60, charIdx = 0; //行、行高(建议略大于字号)、字符索引
- let linear = ctx.createLinearGradient(0, 0, w, h);
- linear.addColorStop(0, 'red');
- linear.addColorStop(0.3, 'olive');
- linear.addColorStop(0.7, 'darkgreen');
- linear.addColorStop(1, 'orange');
- (function drawText() {
- ctx.clearRect(0, 0, w, h);
- ctx.strokeStyle = linear;
- ctx.font = 'bold 50px snas-serif';
- for(let k = 0; k < lineNow; k ++) {
- ctx.strokeText(txtAr[k], 20, lineHeight * k + lineHeight);
- }
- let txtstr = txtAr[lineNow].substring(0, charIdx);
- ctx.strokeText(txtstr, 20, lineHeight * lineNow + lineHeight);
- charIdx ++;
- if(charIdx > txtAr[lineNow].length) {
- lineNow += 1;
- charIdx = 0;
- }
- if(lineNow > txtAr.length - 1) lineNow = 0;
- setTimeout(drawText, 500);
- })();
- </script>
复制代码
|
|