如何通过传递名称返回头像图标

时间:2016-09-27 11:37:38

标签: javascript jquery sapui5

我要求通过传递名称它应该返回一个头像 icon包含该名称中包含的单词的第一个字母。例如,如果我通过John Abraham它应该返回一个图标'JA'。我需要在sapui5控件中使用该图标。我对此没有任何想法。如何实现这一点?感谢任何帮助。

我需要像这样的头像图标。你可以看到带有字母V的图标。avatar icon

谢谢,

5 个答案:

答案 0 :(得分:2)

画布回答是在正确的轨道上,但在您的情况下,您需要一个数据网址,您可以将其分配给您的控件srcicon属性。

以下示例中的generateAvatar函数将名称(字符串)转换为图像数据url(在url中将图像包含为base64 gif)。可以将数据URL分配给UI5控件上的Buttons icon property或任何其他图像url属性。您甚至可以将它用作带数据绑定的格式化程序函数,如下例所示。

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.
}

JSBin

上的示例

答案 1 :(得分:1)

在这里查看演示。

JS BIN

您可以阅读有关canvas here

的更多信息

答案 2 :(得分:1)

自UI5 1.46.x 起,此类头像图标控件即可使用。

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

* sap.f(如果UI5版本低于1.73)。否则,请改用Avatar中的sap.m

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

OpenUI5 Avatar control with initials

可以在https://openui5.hana.ondemand.com/entity/sap.m.Avatar中找到更多示例。

答案 3 :(得分:0)

分叉@Sathvik Cheela代码以满足您的要求:

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

答案 4 :(得分:0)

您可以为此创建自定义UI5控件。它也支持数据绑定:)

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