用字母替代图片脚本:LetterAvatar

Plugins162.2K阅读模式

基于canvas,通过toDataURL动态生成base64图片。目前我主题的Gravatar头像,就是利用这个LetterAvatar脚本实现未设置Gravatar头像则读取ALT标签,自动生成首字图片替代默认的头像图片。

用字母替代图片脚本:LetterAvatar

之前已有WP爱好者制作了一款:mk-letter-avatar 字母头像插件,试了一下很好用,不过打开浏览器开者工具发现产生大量404错误,看了一下源代码,该插件是通过无头像返回404错误,触发onerror事件用自动生成的字母图片替换src图片地址,判断方式不是很合理,如果不是因为个缺点我都想直接拿来用了,如果作者再优化一下,绝对是款优秀实用的插件。

我的实现原理和插件不同,配合头像本地缓存功能,判断无头像后,直接为无头像的图片添加特定的class类,然后通过LetterAvatar脚本替换图片。

需要注意的是上面提到的插件,Gravatar头像图片必须有alt标签属性,否则不会生成正常的图片,可惜大部分主题默认Gravatar头像alt标签属性是空的.....

如果想自动为Gravatar头像添加alt标签属性,可以将下面的代码添加到当前主题函数模板functions.php中:

function zm_gravatar_alt($altgravatar) {
	if (have_comments()) {
		$alt = get_comment_author();
	}
	else {
		$alt = get_the_author_meta('display_name');
	}
	$altgravatar= str_replace('alt=\'\'', 'alt=\'' . $alt . '\' title=\'Gravatar for ' . $alt . '\'', $altgravatar);
	return $altgravatar;
}
add_filter('get_avatar', 'zm_gravatar_alt');

之后,自动将评论者昵称做为alt属性。

本文只是自己做个记录,并不是教大家怎么弄这个头像,如果认为这字母头像还不错,请直接使用上面介绍的插件。

展开收缩

另附LetterAvatar脚本演示代码:

<!DOCTYPE html>
<html>
<h1>Letter Avatar</h1>

<small><strong>用法:</strong></small>
<pre>
<code>&lt;img src=&quot;&quot; class=&quot;avatar photo&quot; width=&quot;256&quot; height=&quot;256&quot; alt=&quot;知更鸟&quot; color=&quot;#c40000&quot;&gt;</code>
</pre>

<img src="" class="avatar photo" height="240" width="240" alt="知更鸟" color="#c40000" />
<img src="" class="avatar photo" height="240" width="240" alt="更鸟" color="#99CC66" />
<img src="" class="avatar photo" height="240" width="240" alt="鸟" color="#0D8ABC" />

<style>
	body {
	  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
	}

	pre {
	  margin: 20px 0;
	  padding: 20px;
	  background: #fafafa;
	}

	.avatar { border-radius: 50%; }
</style>
<script src="http://libs.baidu.com/jquery/3.2.1/jquery.min.js "></script>
<script>
	/*
	 * LetterAvatar
	 * 
	 * Artur Heinze
	 * Create Letter avatar based on Initials
	 * based on https://gist.github.com/leecrossley/6027780
	 */
	(function(w, d){
		function LetterAvatar (name, size, color) {

			name  = name || '';
			size  = size || 60;

			var colours = [
					"#1abc9c", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#2c3e50", 
					"#f1c40f", "#e67e22", "#e74c3c", "#ecf0f1", "#95a5a6", "#f39c12", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"
				],

				nameSplit = String(name).split(' '),
				initials, charIndex, colourIndex, canvas, context, dataURI;


			if (nameSplit.length == 1) {
				initials = nameSplit[0] ? nameSplit[0].charAt(0):'?';
			} else {
				initials = nameSplit[0].charAt(0) + nameSplit[1].charAt(0);
			}

			if (w.devicePixelRatio) {
				size = (size * w.devicePixelRatio);
			}
				
			charIndex     = (initials == '?' ? 72 : initials.charCodeAt(0)) - 64;
			colourIndex   = charIndex % 20;
			canvas        = d.createElement('canvas');
			canvas.width  = size;
			canvas.height = size;
			context       = canvas.getContext("2d");
			 
			context.fillStyle = color ? color : colours[colourIndex - 1];
			context.fillRect (0, 0, canvas.width, canvas.height);
			context.font = Math.round(canvas.width/2)+"px Arial";
			context.textAlign = "center";
			context.fillStyle = "#FFF";
			context.fillText(initials, size / 2, size / 1.5);

			dataURI = canvas.toDataURL();
			canvas  = null;

			return dataURI;
		}

		LetterAvatar.transform = function() {

			Array.prototype.forEach.call(d.querySelectorAll('img[alt]'), function(img, name, color) {
				name = img.getAttribute('alt');
				color = img.getAttribute('color');
				img.src = LetterAvatar(name, img.getAttribute('width'), color);
				img.removeAttribute('avatar');
				img.setAttribute('alt', name);
			});
		};


		// AMD support
		if (typeof define === 'function' && define.amd) {
			
			define(function () { return LetterAvatar; });
		
		// CommonJS and Node.js module support.
		} else if (typeof exports !== 'undefined') {
			
			// Support Node.js specific `module.exports` (which can be a function)
			if (typeof module != 'undefined' && module.exports) {
				exports = module.exports = LetterAvatar;
			}

			// But always support CommonJS module 1.1.1 spec (`exports` cannot be a function)
			exports.LetterAvatar = LetterAvatar;

		} else {
			
			window.LetterAvatar = LetterAvatar;

			d.addEventListener('DOMContentLoaded', function(event) {
				LetterAvatar.transform();
			});
		}
	})(window, document);
</script>
</html>

原项目地址:https://github.com/daolavi/LetterAvatar

本站文章大部分始于原创,用于个人学习记录,可能对您有所帮助,仅供参考!

weinxin
我的微信
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
 
知更鸟
评论  16  访客  14  作者  2
    • 简单生活
      简单生活 4

      沙发是我的,哈哈,鸟哥考虑下吧qq快速评论和昵称输入框合并下,看有的主题有这个,挺方便

      • 虫子君
        虫子君 4

        鸟叔请教一个小妙招,我想要实现登陆才能看到下载按钮,怎么实现?之前是评论下载,现在不能评论了,所以干脆改成登陆下载。

          • 绿软吧
            绿软吧 5

            @ 虫子君 判断登陆,然后输出下载地址
            如果用户没登录就提前登录才能查看

          • Wood Hong
            Wood Hong 2

            哇 上了ssl的船了 难怪一早打开 就不正常了

            • 哈灵游戏
              哈灵游戏 2

              厉害了,我一会去试试。

              • 小妞
                小妞 0

                鸟哥厉害了

                • 波克麻将
                  波克麻将 1

                  大佬厉害,必须顶一个

                  • mengkun
                    mengkun 1

                    纠正一个细节 :razz: 这个插件是纯原生的,没引入 jQuery 也能使用

                      • 知更鸟
                        知更鸟

                        @ mengkun 嗯,如果没看到你的介绍,还真不知道有这个脚本

                          • mengkun
                            mengkun 1

                            @ 知更鸟 自动加 alt 很赞!已经集成在最新版的插件中了 :grin:

                        • 板凳
                          板凳 0

                          这个具体怎么使用呢,谢谢

                          • 黑山老妖朋友
                            黑山老妖朋友 0

                            请问添加了 functions.php 的那段代码。那个脚本演示代码放哪里呢,谁能告诉我下具体使用步骤呢?万分感谢!

                            • 才华无限
                              才华无限 4

                              这个看着不错,有个性。

                              • 麻雀
                                麻雀 1

                                按鸟哥的介绍,装了mk-letter-avatar 字母头像插件,主题函数模板functions.php中也加入了对应的代码,但是只是后台字母头像都正常显示,但是前台不显示字母头像,开启缓存,前台虽然随机头像已经选项已经关闭,但是还是显示早先的无头像随机图片,不知道什么原因。希望有高手指点下,谢谢

                              匿名

                              发表评论

                              匿名网友
                              :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

                              拖动滑块以完成验证