how to return avatar icon by passing a name

I have a requirement that by passing a name it should return an avatar icon contains the first letters of the words contained in that name.For instance, if I pass John Abraham it should return an icon '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 need avatar icon like this.You can see the icon with letter V in this.avatar icon

Thank You,

Answers:

Answer

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

Answer

Check the demo here.

JS BIN

You can read more about canvas here

Answer

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);
<!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>

Answer

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 common 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());
  }
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.