最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to display avatar icon with dynamically created name initials - Stack Overflow

programmeradmin3浏览0评论

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 John Abraham, it should return an icon with 'JA'.

I need to use that icon in an SAPUI5 control. I do not have any idea on this. How to implement this? Any help is appreciated.

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 John Abraham, it should return an icon with 'JA'.

I need to use that icon in an SAPUI5 control. I do not have any idea on this. How to implement this? Any help is appreciated.

Share Improve this question edited Jun 9, 2020 at 10:25 Boghyon Hoffmann 18.1k14 gold badges93 silver badges202 bronze badges asked Sep 27, 2016 at 11:37 vijayalalithavijayalalitha 571 gold badge2 silver badges8 bronze badges 2
  • For readers with UI5 1.46 and above: see stackoverflow./a/62280337/5846045 – Boghyon Hoffmann Commented Jun 9, 2020 at 10:23
  • Please consider to accept the answer to help future readers finding the latest solution. – Boghyon Hoffmann Commented Jun 11, 2020 at 11:17
Add a ment  | 

4 Answers 4

Reset to default 11

The canvas answeres are on the right track, but in your case you need a data url that you can assign to your controls src or icon property.

The generateAvatar function in the following example converts a name (string) to a image data url (contains the image as base64 gif in the url). The data url can be assigned to the Buttons icon property or any other image url property on a UI5 control. And you can even use it as a formatter function with databinding as in the following example.

var model = new sap.ui.model.json.JSONModel({
  name: "John Doe"
});

new sap.m.Input({value:"{/name}", valueLiveUpdate:true}).setModel(model).placeAt("body");

new sap.m.Button({
  icon:{path: "/name", formatter: generateAvatar},
  text:"Hello"
}).setModel(model).placeAt("body");


function generateAvatar(name){
  var initials = name.split(' ').map(function(str) { return str ? str[0].toUpperCase() : "";}).join('');
  var canvas = document.createElement('canvas');
  var radius = 30;
  var margin = 5;
  canvas.width = radius*2+margin*2;
  canvas.height = radius*2+margin*2;

  // Get the drawing context
  var ctx = canvas.getContext('2d');
  ctx.beginPath();
  ctx.arc(radius+margin,radius+margin,radius, 0, 2 * Math.PI, false);
  ctx.closePath();
  ctx.fillStyle = 'grey';
  ctx.fill();
  ctx.fillStyle = "white";
  ctx.font = "bold 30px Arial";
  ctx.textAlign = 'center';
  ctx.fillText(initials, radius+5,radius*4/3+margin);
  return canvas.toDataURL();
  //The canvas will never be added to the document.
}

Example on JSBin

Since UI5 1.46.x, such avatar icon controls are available out of the box.

<Avatar xmlns="sap.m"|"sap.f"*
  initials="{ path: 'name', formatter: '.createInitials' }"
  displayShape="Square"
/>

* sap.f if UI5 version is lower than 1.73. Otherwise, use the Avatar from sap.m instead!

createInitials: function(name) { // minimal sample
  return name.split(" ").map(str => str[0]).join("");
},

More samples can be found in https://openui5.hana.ondemand./entity/sap.m.Avatar.

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./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);
<!DOCTYPE html>
<html>

<head>

  <meta charset=utf-8 />
  <title>JS Bin</title>
</head>

<body>

  Text:
  <input id="input" type="text" value="John Doe">

</body>

</html>

You could create a custom UI5-control for that. It supports databinding too :)

Example on JSBin:

var NameIcon = sap.ui.core.Control.extend("NameIcon", { // call the new Control type "NameIcon" and let it inherit
                                     // from sap.ui.core.Control

  // the Control API:
  metadata : {
      properties : {           // setter and getter are created behind the scenes, 
                               // incl. data binding and type validation
          "name" : "string",   // in simple cases, just define the type
          "size" : {type: "sap.ui.core.CSSSize", defaultValue: "40px"} 
                               // you can also give a default value and more
      }
  },


  // the part creating the HTML:
  renderer : function(oRm, oControl) { // static function, so use the given "oControl" instance 
                                       // instead of "this" in the renderer function

      oRm.write("<div"); 
      oRm.writeControlData(oControl);  // writes the Control ID and enables event handling - important!
      oRm.addStyle("width", oControl.getSize());  // write the Control property size; the Control has validated it 
                                                  // to be a CSS size
      oRm.addStyle("height", oControl.getSize());
      oRm.addStyle("border-radius", "50%");

      oRm.addStyle("text-align","center"); //Center text
      oRm.addStyle("vertical-align","middle");
      oRm.addStyle("line-height", oControl.getSize());

      oRm.addStyle("font-family","Arial,Helvetica,sans-serif;")
      oRm.addStyle("background-color", "steelblue");
      oRm.addStyle("color","white")

      oRm.writeStyles();
      //oRm.addClass("sapMTitle");        // add a CSS class for styles mon to all Control instances
      oRm.writeClasses();              // this call writes the above class plus enables support 
                                       // for Square.addStyleClass(...)

      oRm.write(">");
      oRm.writeEscaped(oControl.getInitials()); // write another Control property, with protection 
                                            // against cross-site-scripting
      oRm.write("</div>");
  },
  getInitials:function(){
    var name = this.getName();
    if (!name) return "";
    var parts = name.split(" ");
    var result = parts.map(function(p){return p.charAt(0).toLocaleUpperCase();}).join("");
    return result;
  },
  // an event handler:
  onclick : function(evt) {   // is called when the Control's area is clicked - no event registration required
      alert("Control clicked! Text of the Control is:\n" + this.getText());
  }
});
发布评论

评论列表(0)

  1. 暂无评论