How to display avatar icon with dynamically created name initials

前端 未结 4 462
眼角桃花
眼角桃花 2021-01-14 12:34

I have a requirement that, by passing a name, it should return an avatar icon which contains the first letters of the words contained in that name. For instance: if I pass

4条回答
  •  春和景丽
    2021-01-14 13:05

    Forked @Sathvik Cheela code to meet your requirements:

    console.clear()
    var CVS = document.createElement('canvas'),
      ctx = CVS.getContext('2d');
    
    CVS.width = 500;
    CVS.height = 500;
    document.body.appendChild(CVS); // Add canvas to DOM
    
    // Transform input text 
    function transformText(text) {
      return text
        .split(' ')
        .map((str) => str ? str[0].toUpperCase() : "")
        .join('')
    }
    
    // GRAPHICS TO CANVAS /////
    function sendToCanvas(ob) {
        var img = new Image();
        img.onload = function() {
          ctx.drawImage(img, 0, 0);
          ctx.font = ob.fontWeight + ' ' + ob.fontSize + ' ' + ob.fontFamily;
          ctx.textAlign = 'center';
          ctx.fillStyle = ob.color;
          ctx.fillText(transformText(ob.text), CVS.width - 350, CVS.height / 3);
        };
        img.src = ob.image;
      }
      ///////////////////////////
    
    // DO IT! /////////////////
    
    var cvsObj = {
      image: "http://www.polyvore.com/cgi/img-thing?.out=jpg&size=l&tid=31228042",
      text: "john doe",
      fontFamily: "Arial",
      fontWeight: "bold",
      fontSize: "30px",
      color: "rgba(0, 0, 0, 0.7)"
    };
    sendToCanvas(cvsObj);
    
    
    
    document.getElementById('input').addEventListener('input', function() {
      cvsObj.text = this.value;
      sendToCanvas(cvsObj);
    }, false);
    
    
    
    
    
      
      JS Bin
    
    
    
    
      Text:
      
    
    
    
    

提交回复
热议问题