Canvas生成姓名文字头像

很多项目管理工具都会有姓名文字头像这样一个功能,这样便于管理者或者成员更容易找到成员相关的内容,对于生成这样的图片方法很多,后端,前端均可生成,下面演示一个用canvas生成文字头像的例子。

代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>名字头像</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
</head>
<body>

<div style="text-align: center">


			<input type="text" id="name">
			<button id="gernate">生成</button>
		

		<canvas id="gavatar"></canvas>
	</div>

    <script type="text/javascript">
    	var nameGavatar  = (function(){
    		var width,height,canvas,ctx,params;
    		var defaults = {
    			canvasId : '',
    			text : '',
    			width : 100,
    			height : 100,
    			backColor : '#eee',
    			textColor : '#f00',
    			fontFamily : '微软雅黑'
    		}
    		function init(params){
    			extend(defaults,params);
    			if(!defaults.canvasId) { throw new Error("lack of gavatar element"); }
    			canvas = document.getElementById(defaults.canvasId);
    			ctx = canvas.getContext("2d");
    			canvas.width = defaults.width;
    			canvas.height = defaults.height;
    			gernate();
   				
    		}
    		function gernate(texts){
    			var text = texts || defaults.text;
    			width = defaults.width;
    			height = defaults.height;
    			fontSize = width / (text.length + 1);
    			var x = width/ 2,y = height / 2;
   				ctx.fillStyle = defaults.backColor;
   				ctx.fillRect(0,0,width,height);
   				ctx.textBaseline = "middle";
   				ctx.textAlign = "center";
   				ctx.fillStyle = defaults.textColor;
   				ctx.font = fontSize + "px " + defaults.fontFamily;
   				ctx.fillText(text,x,y);
    		}
    		function extend(defaults,params){
    			for(var index in params){
    				defaults[index] = params[index];
    			}
    		}
    		return { 
    			init : init,
    			gernate : gernate
    		};
    	})();
    	nameGavatar.init({
    		canvasId : 'gavatar',
    		text : '韩超'
    	});
    	gernate.onclick = function(){
    		console.log(document.getElementById("name").value)
    		nameGavatar.gernate(document.getElementById("name").value);
    	}
    </script>
</body>
</html>

在线Demo:http://demo.deanhan.cn/text-gavatar

  • 支付宝二维码 支付宝
  • 微信二维码 微信
相关文章