实用单字图片生成Jquery代码
6
2025-07-07
众所周知。做导航站的就是logo图片容易失效,保存到本地又占空间,批量维护又浪费时间。
哎!有没有图片一失效就使用文字作为当前的Logo呢?有的有的,有很多种方法。但我比较推荐使用JS方法。
这种方法数据过多会卡,但也是较好的方法了,配合懒加载,图片失效则生成单字图片
详细可看我首页
代码如下:
//参数分别是 $("img"),文字,图片大小,背景图片。后2个参数可默认不填
例如:<img src="" onerror="danzitu(this,'文字')">,图片失效则执行
function danzitu(imgElement, name, size = 80, color) {
const colors = "#1abc9c #2ecc71 #3498db #9b59b6 #34495e #16a085 #27ae60 #2980b9 #8e44ad #2c3e50 #f1c40f #e67e22 #e74c3c #00bcd4 #95a5a6 #f39c12 #d35400 #c0392b #bdc3c7 #7f8c8d".split(" ");
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d");
name = String(name || "").split(" ");
name = name.length === 1 ? name[0].charAt(0) : name[0].charAt(0) + name[1].charAt(0);
const colorIndex = (name.charCodeAt(0) - 64) % colors.length;
ctx.fillStyle = color || colors[colorIndex];
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.font = `${Math.round(canvas.width / 2)}px 'Microsoft Yahei'`;
ctx.textAlign = "center";
ctx.fillStyle = "#FFF";
ctx.fillText(name, size / 2, size / 1.5);
imgElement.src = canvas.toDataURL();
};
更新时间:2025-07-07 13:45:47
本文地址:https://www.xmnav.cn/post/27.html
版权声明:本站所发布的全部内容源于互联网搬运,仅限于小范围内传播学习和文献参考,请在下载后24小时内删除。如果有侵权之处请第一时间联系我们删除,敬请谅解!kihaluge@qq.com