为了让用户能够输入自己的姓名,您需要一个文本字段。您还需要一个按钮来触发 Javascript 函数,该函数检查文本字段的值并呈现字母图像。
您可以使用以下代码来创建字母。您将需要一个带有 id 'textfield' 的文本字段和一个 div 来呈现带有 id 'output' 的结果,当然您可以更改它。我建议使用 select 元素来存储模式选项(本例中为#patternChooser)
function renderName()
{
// Get the name to be rendered and the chosen pattern
var text = document.getElementById('textfield').value;
var pattern = document.getElementById('patternChooser').value;
// Iterate over the name and create an element for each letter
for(i = 0; i < text.length; i++)
{
var letter = document.createElement('div');
letter.style.backgroundImage = 'url(' + pattern + '_' + text[i] + ')';
document.getElementById('output').appendChild(letter);
}
}
您可以使用以下 CSS 对字母应用一些定位(调整图片的宽度和高度):
#output div
{
margin-left: 10px;
width: 50px;
height: 100px;
float: left;
}
您需要将图像命名为:flowerpattern_a.png、brickpattern_j.png 等。
如果您希望字母实时显示,您可以使用 Javascript 的 onkeyup() 触发一个函数,该函数检查文本字段值的最后一个字符并为其创建一个元素。
精灵
您还可以使用精灵来提高性能。将字母的所有图像放入一张图像中。您将此图像设置为每个字母的背景。
快速阅读 CSS 精灵:http://css-tricks.com/css-sprites/
您可以在上面的 CSS sn-p 中添加background-image: url(sprite.png);。
您需要设置字母的背景位置(letter.style.background-position = '100px 200px')
,而不仅仅是使用 Javascript 设置 backgroundImage
字体嵌入
如果您要使用字体:有很多字体嵌入选项,例如 Typeface 和 Cufon。我觉得最愉快的工作是使用font-face。它速度很快,并且文本的行为与任何其他文本一样。
如果您有 .TTF Truetype 字体,则需要将字体转换为 .EOT 以用于 Internet Explorer。您还可以添加 SVG 字体以实现完整的浏览器覆盖。这实际上非常简单:您只需将以下 sn-p 添加到样式表的顶部,如下所示:
@font-face {
font-family: 'GothicCustom';
src: url("LeagueGothic.eot");
src: local('League Gothic'),
url("LeagueGothic.svg#lg") format('svg'),
url("LeagueGothic.otf") format('opentype');
}
这种技术的优势在于它易于使用,并且您可以完全控制呈现的文本,就像您网站上的任何其他文本一样。您可以设置字体大小、字母间距等Here's a good read about font-face font embedding。
您可以使用Microsoft WEFT 或TTF2EOT 创建.EOT 字体。
例如,您的代码可能如下所示。
Javascript
function renderName()
{
// Get the name to be rendered and the chosen pattern
var text = document.getElementById('textfield').value;
var pattern = document.getElementById('patternChooser').value;
// Render the text with a class
for(i = 0; i < text.length; i++)
{
var output = document.getElementById('output');
output.style.fontFamily = pattern;
output.innerHTML = text;
}
}
HTML
<form>
<input id="textfield" type="text" />
<select id="patternChooser">
<option>Flowers</option>
<option>Brick</option>
<option>Decorative</option>
</select>
<input type="button" onclick="renderName()" />
</form>
<div id="output"></div>
CSS
@font-face {
font-family: 'Decorative';
src: url("decorative.eot");
src: local('Decorative'),
url("Decorative.svg#lg") format('svg'),
url("Decorative.otf") format('opentype');
}
现在唯一剩下的就是转换字体并将它们导入到您的样式表中。
当然,您可以选择使用任何其他字体嵌入方法。 Here's an article about font-embedding options 但快速的 Google 也会向您显示选项。