实现效果
LetterAvatar的原理就是利用了浏览器对象canvas
在线体验:.html
LetterAvatar.js 完整代码
/** LetterAvatar* * Artur Heinze* Create Letter avatar based on Initials* based on */
(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 = Context("2d");context.fillStyle = color ? color : colours[colourIndex - 1];context.fillRect (0, 0, canvas.width, canvas.height);context.font = und(canvas.width/2)+"px Arial";Align = "center";context.fillStyle = "#FFF";context.fillText(initials, size / 2, size / 1.5);dataURI = DataURL();canvas = null;return dataURI;}ansform = function() {Array.prototype.forEach.call(d.querySelectorAll('img[avatar]'), function(img, name, color) {name = Attribute('avatar');color = Attribute('color');img.src = LetterAvatar(name, Attribute('width'), color);veAttribute('avatar');img.setAttribute('alt', name);});};// AMD supportif (typeof define === 'function' && define.amd) {define(function () { return LetterAvatar; });// CommonJS and Node.js module support.} else if (typeof exports !== 'undefined') {// Support Node.js specific ports` (which can be a function)if (typeof module != 'undefined' && ports) {exports = ports = 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) {ansform();});}
})(window, document);
可以在浏览器中直接使用
<img width="256" height="256" avatar="Dao Lam" color="#0D8ABC">
参考文章
本文发布于:2024-01-27 21:31:19,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/17063622802752.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |