HTML中使用用户名首字母作为头像显示



<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <title>title>
    <link type="text/css" href="https://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <script type="text/javascript" src="https://cdn.bootcss.com/jquery/2.2.0/jquery.min.js">script>
    <script type="text/javascript" src="https://cdn.bootcss.com/bootstrap/3.3.6/js/bootstrap.min.js">script>
head>
<body>

    <img src="" class="img-circle headImg" alt="User Image">
    <canvas id="headImg" style="display:none">canvas>

    <script type="text/javascript">
        $(function(){
            textToImg();
        });

        function textToImg() {
            var uname = 'Joy';
            var name = uname.charAt(0);
            var fontSize = 60;
            var fontWeight = 'bold';

            var canvas = document.getElementById('headImg');
            var img1 = document.getElementById('headImg');
            canvas.width = 120;
            canvas.height = 120;
            var context = canvas.getContext('2d');
            context.fillStyle = '#F7F7F9';
            context.fillRect(0, 0, canvas.width, canvas.height);
            context.fillStyle = '#605CA8';
            context.font = fontWeight + ' ' + fontSize + 'px sans-serif';
            context.textAlign = 'center';
            context.textBaseline="middle";
            context.fillText(name, fontSize, fontSize);
            $('.headImg').attr('src',canvas.toDataURL("image/png"));
        };
    script>
body>
html>

你可能感兴趣的:(javascript)