Toast.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //一个简单的tost组件,用法:
  2. // let Toast = reqire('Toast.js')
  3. // Toast(text,{gravity,duration,bg_color})
  4. //text:要显示的字符串
  5. //gravity(可选):位置,String类型,可选值('CENTER','TOP','BOTTOM'),默认为'CENTER'
  6. //duration(可选):时间,Number类型,单位为秒,默认1s
  7. //bg_color(可选):颜色,cc.color类型,默认cc.color(102, 102, 102, 200)
  8. function Toast(
  9. text = "",
  10. {
  11. gravity = "CENTER",
  12. duration = 1,
  13. bg_color = cc.color(102,102,102,200)
  14. } = {}
  15. ){
  16. //canvas
  17. let canvas = cc.director.getScene().getComponentInChildren(cc.Canvas);
  18. let width = canvas.node.width;
  19. let height = canvas.node.height;
  20. let bgNode = new cc.Node();
  21. //Label文本格式设置
  22. let textNode = new cc.Node();
  23. let textLabel = textNode.addComponent(cc.Label);
  24. textLabel.horizontalAlign = cc.Label.HorizontalAlign.CENTER;
  25. textLabel.verticalAlign = cc.Label.VerticalAlign.CENTER;
  26. textLabel.fontSize = 30;
  27. textLabel.string = text;
  28. //当文本宽度过长时,设置为自动换行格式
  29. if (text.length * textLabel.fontSize > (width * 3) / 5){
  30. textNode.width = (width * 3) / 5;
  31. textLabel.overflow = cc.Label.Overflow.RESIZE_HEIGHT;
  32. }else {
  33. textNode.width = text.length * textLabel.fontSize;
  34. }
  35. let lineCount = ~~((text.length * textLabel.fontSize) / ((width * 3) / 5)) + 1;
  36. textNode.height = textLabel.fontSize * lineCount;
  37. //背景设置
  38. let ctx = bgNode.addComponent(cc.Graphics);
  39. ctx.arc(
  40. -textNode.width / 2,
  41. 0,
  42. textNode.height / 2 + 20,
  43. 0.5 * Math.PI,
  44. 1.5*Math.PI,
  45. true
  46. );
  47. ctx.lineTo(textNode.width / 2, -(textNode.height / 2 + 20));
  48. ctx.arc(
  49. textNode.width / 2,
  50. 0,
  51. textNode.height / 2 + 20,
  52. 1.5 * Math.PI,
  53. 0.5 * Math.PI,
  54. true
  55. );
  56. ctx.lineTo(-textNode.width / 2, textNode.height / 2 + 20);
  57. ctx.fillColor = bg_color;
  58. ctx.fill();
  59. bgNode.addChild(textNode);
  60. // gravity 设置Toast显示的位置
  61. if (gravity === "CENTER"){
  62. bgNode.y = 0;
  63. bgNode.x = 0;
  64. }else if (gravity === "TOP"){
  65. bgNode.y = bgNode.y + (height / 5) * 2;
  66. }else if (gravity === "BOTTOM"){
  67. bgNode.y = bgNode.y - (height / 5) * 2;
  68. }
  69. canvas.node.addChild(bgNode);
  70. let finished = cc.callFunc(function (){
  71. bgNode.destroy();
  72. });
  73. let action = cc.sequence(
  74. cc.moveBy(duration, cc.v2(0, 0)),
  75. cc.fadeOut(0.3),
  76. finished
  77. );
  78. bgNode.runAction(action);
  79. }
  80. module.exports = Toast;