这个想法是你的元素与文本和canvas 元素
是一个在另一个之上。您将文本保留在元素中(在
为了允许文本选择,canvas 无法做到这一点
文本),但使其完全透明(使用rgba(0,0,0,0),在
为了让文本在 IE8 和更早版本中可见 - 那是因为你
在 IE8 和更早版本中不支持 RGBa 和不支持 canvas)。
然后您读取元素内的文本并将其写在画布上
具有相同的字体属性,这样你写的每个字母
画布是在元素中对应的字母与文本。
canvas 元素不支持多行文本,因此您将拥有
将文本分解成单词,然后继续在测试行上添加单词
然后测量。如果测试线占用的宽度更大
比你可以拥有的一条线的最大允许宽度(你明白了
通过读取元素的计算宽度来允许的最大宽度
与文本),然后你把它写在画布上而不用最后一个字
添加,您将测试行重置为最后一个单词,然后增加
将下一行写入一个行高的 y 坐标
(您还可以从元素的计算样式中获得
文本)。随着你写的每一行,你也降低了不透明度
带有适当步骤的文本(此步骤相反
与每行的平均字符数成正比)。
在这种情况下你不能轻易做的是证明文本的合理性。有可能
完成了,但它变得有点复杂,这意味着你会有
计算每一步应该有多宽,并写下文本单词
一个字一个字,而不是一行字。
另外,请记住,如果您的文本容器的宽度随您更改
调整窗口大小,然后您必须清除画布并重新绘制
每次调整大小时都会在其上显示文字。
好的,代码:
HTML:
<article>
<h1>Interacting Spiral Galaxies NGC 2207/ IC 2163</h1>
<em class='timestamp'>February 4, 2004 09:00 AM</em>
<section class='article-content' id='art-cntnt'>
<canvas id='c' class='c'></canvas>In the direction of <!--and so on-->
</section>
</article>
CSS:
html {
background: url(moving.jpg) 0 0;
background-size: 200%;
font: 100%/1.3 Verdana, sans-serif;
animation: ani 4s infinite linear;
}
article {
width: 50em; /* tweak this ;) */
padding: .5em;
margin: 0 auto;
}
.article-content {
position: relative;
color: rgba(0,0,0,0);
/* add slash at the end to check they superimpose *
color: rgba(255,0,0,.5);/**/
}
.c {
position: absolute;
z-index: -1;
top: 0; left: 0;
}
@keyframes ani { to { background-position: 100% 0; } }
JavaScript:
var wrapText = function(ctxt, s, x, y, maxWidth, lineHeight) {
var words = s.split(' '), line = '',
testLine, metrics, testWidth, alpha = 1,
step = .8*maxWidth/ctxt.measureText(s).width;
for(var n = 0; n < words.length; n++) {
testLine = line + words[n] + ' ';
metrics = ctxt.measureText(testLine);
testWidth = metrics.width;
if(testWidth > maxWidth) {
ctxt.fillStyle = 'rgba(0,0,0,'+alpha+')';
alpha -= step;
ctxt.fillText(line, x, y);
line = words[n] + ' ';
y += lineHeight;
}
else line = testLine;
}
ctxt.fillStyle = 'rgba(0,0,0,'+alpha+')';
alpha -= step;
ctxt.fillText(line, x, y);
return y + lineHeight;
}
window.onload = function() {
var c = document.getElementById('c'),
ac = document.getElementById('art-cntnt'),
/* use currentStyle for IE9 */
styles = window.getComputedStyle(ac),
ctxt = c.getContext('2d'),
w = parseInt(styles.width.split('px')[0], 10),
h = parseInt(styles.height.split('px')[0], 10),
maxWidth = w,
lineHeight = parseInt(styles.lineHeight.split('px')[0], 10),
x = 0,
y = parseInt(styles.fontSize.split('px')[0], 10),
text = ac.innerHTML.split('</canvas>')[1];
c.width = w;
c.height = h;
ctxt.font = '1em Verdana, sans-serif';
wrapText(ctxt, text, x, y, maxWidth, lineHeight);
};