微信授權、排行、分享

授權

Platform.ts

/** 
 * 平臺數據接口。
 * 由於每款遊戲通常需要發佈到多個平臺上,所以提取出一個統一的接口用於開發者獲取平臺數據信息
 * 推薦開發者通過這種方式封裝平臺邏輯,以保證整體結構的穩定
 * 由於不同平臺的接口形式各有不同,白鷺推薦開發者將所有接口封裝爲基於 Promise 的異步形式
 */
declare interface Platform {

    getUserInfo(): Promise<any>;

    login(): Promise<any>

    getPlatformSign(): Promise<any>;

    shareAppMessage(): Promise<any>;
    openDataContext: any;

}

class DebugPlatform implements Platform {

    async getUserInfo() {
        return { nickName: "username" }
    }

    async login() {

    }

    async getPlatformSign() {
        return { platform: "h5" };
    }

    async shareAppMessage() {
        return { shareName: "share" };

    }

    openDataContext: any;
}


if (!window.platform) {
    window.platform = new DebugPlatform();
}


declare let platform: Platform;

declare interface Window {

    platform: Platform
}





導出的微信工程 platform.js中添加

/**
 * 請在白鷺引擎的Main.ts中調用 platform.login() 方法調用至此處。
 */

class WxgamePlatform {

  name = 'wxgame'

  getPlatformSign() {
    return {
      platform: "wx"
    };
  }

  login() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          console.log("login  res ", res);
          resolve(res)
        }
      })
    })
  }

  shareAppMessage(){
    return new Promise((resolve,reject)=>{
      wx.shareAppMessage({
          title: "我的小遊戲", //轉發標題
          // imageUrl: "resource/assets/games/miner/image/icon_player_push1.png",    //轉發圖片
          imageUrl:"https://mmocgame.qpic.cn/wechatgame/fewfewfsHufpmQFqJzoBzzIpoEnQ1ticnWrCqCpWdte5Bq2CKI1G7p2MudsfewfzK/0",
          desc:"快來一起玩啊",
          success: function (res) {
          // 轉發成功
           console.log("轉發成功");
           resolve()
          },
          fail: function (res) {
          // 轉發失敗
           console.log("轉發失敗");
           reject();
          }
      })
    });
  }

  getUserInfo() {
    return new Promise((resolve, reject) => {
      let sysInfo = wx.getSystemInfoSync();
      let sdkVersion = sysInfo.SDKVersion;
      sdkVersion = sdkVersion.replace(/\./g, "");
      sdkVersion = sdkVersion.substr(0, 3);
      let sdkVersionNum = parseInt(sdkVersion);
      //判斷用戶是否授權過
      wx.getSetting({
        success(res) {
          if (sdkVersionNum >= 201 && !res.authSetting['scope.userInfo']) {
            //獲取微信界面大小
            let width = sysInfo.screenWidth;
            let height = sysInfo.screenHeight;

            let xPercent = (720 - 262) / 2 / 720;
            let yPercent = (1280 - 98) / 2 / 1280;
            let wPercent = (260 / 720);
            let hPercent = (98 / 1280);

            var button = wx.createUserInfoButton({
              type: 'text',
              text: '  ',
              // type: 'image',
              // image: 'http://www.oneh5.com/iptv/h5/egret/billiard/resource/game/jiqiu.png',
              style: {
                left: width * xPercent,
                top: height * yPercent,
                width: width * wPercent,
                height: height * hPercent,
              }
            });
            button.onTap((res) => {
              if (res.userInfo) {
                var userInfo = res.userInfo;
                var nickName = userInfo.nickName;
                var avatarUrl = userInfo.avatarUrl;
                var gender = userInfo.gender; //性別 0:未知、1:男、2:女
                var province = userInfo.province;
                var city = userInfo.city;
                var country = userInfo.country;
                button.destroy();
                resolve(userInfo);
              } else {
                button.destroy();
                resolve(userInfo);
              }
            });
          } else {
            wx.getUserInfo({
              withCredentials: true,
              success: res => {
                var userInfo = res.userInfo;
                var nickName = userInfo.nickName;
                var avatarUrl = userInfo.avatarUrl;
                var gender = userInfo.gender; //性別 0:未知、1:男、2:女
                var province = userInfo.province;
                var city = userInfo.city;
                var country = userInfo.country;
                resolve(userInfo);
              },
              fail: res => {
                wx.showModal({
                  title: '友情提醒',
                  content: '請允許微信獲得授權!',
                  confirmText: "授權",
                  showCancel: false,
                  success: res => {
                    resolve(null);
                  }
                });
              }
            });
          }
        }
      })
    });
  }

  openDataContext = new WxgameOpenDataContext();
}

class WxgameOpenDataContext {

  createDisplayObject(type, width, height) {
    sharedCanvas.width = width;
    sharedCanvas.height = height;
    const bitmapdata = new egret.BitmapData(sharedCanvas);
    bitmapdata.$deleteSource = false;
    const texture = new egret.Texture();
    texture._setBitmapData(bitmapdata);
    const bitmap = new egret.Bitmap(texture);
    bitmap.width = width;
    bitmap.height = height;

    console.log("WX width = ",width,", height = ",height);
    if (egret.Capabilities.renderMode == "webgl") {
      const renderContext = egret.wxgame.WebGLRenderContext.getInstance();
      const context = renderContext.context;
      ////需要用到最新的微信版本
      ////調用其接口WebGLRenderingContext.wxBindCanvasTexture(number texture, Canvas canvas)
      ////如果沒有該接口,會進行如下處理,保證畫面渲染正確,但會佔用內存。
      if (!context.wxBindCanvasTexture) {
        egret.startTick((timeStarmp) => {
          egret.WebGLUtils.deleteWebGLTexture(bitmapdata.webGLTexture);
          bitmapdata.webGLTexture = null;
          return false;
        }, this);
      }
    }
    return bitmap;
  }


  postMessage(data) {
    const openDataContext = wx.getOpenDataContext();
    openDataContext.postMessage(data);
  }

  getUserList(){
    let openContext = wx.getOpenDataContext();
    if (openContext["canvas"]["userDataList"]) {
      let friendDataList = JSON.parse(openContext["canvas"]["userDataList"]);
      console.log("openContext");
      console.log(openContext);
      console.log("friendDataList");
      console.log(friendDataList);
      return friendDataList;
    }
    return null;
  }
}


window.platform = new WxgamePlatform();

微信子域中index.js

/**
 * 微信開放數據域
 * 使用 Canvas2DAPI 在 SharedCanvas 渲染一個排行榜,
 * 並在主域中渲染此 SharedCanvas
 */







/**
 * 資源加載組,將所需資源地址以及引用名進行註冊
 * 之後可通過assets.引用名方式進行獲取
 */
const assetsUrl = {
  icon: "openDataContext/assets/icon.png",
  box: "openDataContext/assets/box.png",
  panel: "openDataContext/assets/panel.png",
  button: "openDataContext/assets/button.png",
  title: "openDataContext/assets/rankingtitle.png"
};

/**
 * 資源加載組,將所需資源地址以及引用名進行註冊
 * 之後可通過assets.引用名方式進行獲取
 */
let assets = {};
console.log();
/**
 * canvas 大小
 * 這裏暫時寫死
 * 需要從主域傳入
 */
let canvasWidth;
let canvasHeight;



//獲取canvas渲染上下文
const context = sharedCanvas.getContext("2d");
context.globalCompositeOperation = "source-over";


/**
 * 所有頭像數據
 * 包括姓名,頭像圖片,得分
 * 排位序號i會根據parge*perPageNum+i+1進行計算
 */
let totalGroup = [];

/**
 * 創建排行榜
 */
function drawRankPanel() {
  //起始id
  const startID = perPageMaxNum * page;
  currentGroup = totalGroup.slice(startID, startID + perPageMaxNum);
  //創建頭像Bar
  drawRankByGroup(currentGroup);
}
/**
 * 根據屏幕大小初始化所有繪製數據
 */
function init() {
  //排行榜繪製數據初始化,可以在此處進行修改
  let data = wx.getSystemInfoSync();
  canvasWidth = data.windowWidth;
  canvasHeight = data.windowHeight;
  // console.log("canvasWidth = ",canvasWidth,canvasHeight,canvasWidth/sharedCanvas.width,canvasHeight/sharedCanvas.height);
  initParams();
}

function initParams(){
    if (!sharedCanvas.width || !sharedCanvas.height) {
      return;
    }
    
    //排行榜繪製數據初始化,可以在此處進行修改
    // console.log("stageWidth = ",stageWidth,", stageHeight = ",stageHeight);
    rankWidth = stageWidth;// stageWidth* 4 / 5;
    rankHeight = stageHeight - 6;//stageHeight * 4 / 5;
    barWidth = rankWidth;// * 4 / 5;
    barHeight = rankHeight/perPageMaxNum;//rankWidth / perPageMaxNum;
    offsetX_rankToBorder = (stageWidth - rankWidth) / 2;
    offsetY_rankToBorder = (stageHeight - rankHeight) / 2;
    preOffsetY = barHeight;//(rankHeight - barHeight) / (perPageMaxNum + 1);//(rankHeight - barHeight) / (perPageMaxNum + 1);

    fontSize = Math.floor(barHeight/(96/30));
    startX = offsetX_rankToBorder + (rankWidth - barWidth) / 2;
    startY = offsetY_rankToBorder;//offsetY_rankToBorder + preOffsetY;
    avatarSize = barHeight * (96/116);//barHeight - 10;
    intervalX = barWidth / 30;
    textOffsetY = (barHeight + fontSize) / 2;
    textMaxSize = barWidth / 3;
    indexWidth = context.measureText("999").width;
    // console.log("intervalX = ",intervalX);
    renderDirty = true;
}

/**
 * 根據當前繪製組繪製排行榜
 */
function drawRankByGroup(currentGroup) {
  for (let i = 0; i < currentGroup.length; i++) {
    const data = currentGroup[i];
    drawByData(data, i);
  }
}

/**
 * 根據繪製信息以及當前i繪製元素
 */
function drawByData(data, i) {
  let x = startX;
  // console.log("startX = ",startX,", ",startY,", ",fontSize);
  //繪製底框
  context_drawImage(assets.box, startX, startY + (i+1) * preOffsetY, barWidth, 2);
  x += 10;
  //設置字體
  context.font = Math.floor(fontSize * 4/5) + "px Arial";
  //繪製序號
  context.fillStyle = "#bc8148"
  context.fillText(data.key + "", x, startY + i * preOffsetY + textOffsetY, textMaxSize);
  x += indexWidth + intervalX;

  //NOTE: pdh 
  let avatarUrl =  data["avatarUrl"];

  if (avatarUrl){
    let headX = x+8;
    const img = wx.createImage();
    img.src = avatarUrl;
    img.onload = () => {
      context.save();
      context.beginPath(); //開始繪製
      // context.arc(headX + (avatarSize / 2), startY + i * preOffsetY + (barHeight - avatarSize) / 2 + (avatarSize / 2), avatarSize / 2, 0, Math.PI * 2, false);
      let ix = 4;
      context.rect(headX+ix, ix + startY + i * preOffsetY + (barHeight - avatarSize) / 2, avatarSize-(ix*2), avatarSize-(ix*2));
      context.clip();

      context.drawImage(img, headX + ix, ix + startY + i * preOffsetY + (barHeight - avatarSize) / 2, avatarSize-(ix*2), avatarSize-(ix*2));
      context.restore(); //恢復之前保存的繪圖上下文 恢復之前保存的繪圖上下午即狀態 還可以繼續繪製
      context_drawImage(assets.icon, headX, startY + i * preOffsetY + (barHeight - avatarSize) / 2, avatarSize, avatarSize);
    }

    img.onerror =()=>{
      renderDirty = true;
    }
  }
  
  //繪製頭像
  // context_drawImage(assets.icon, x, startY + i * preOffsetY + (barHeight - avatarSize) / 2, avatarSize, avatarSize);
  x += avatarSize + intervalX;
  context.font = fontSize + "px Arial";
  //繪製名稱
  context.fillText(data.nickname + "", x, startY + i * preOffsetY + textOffsetY, textMaxSize);
  x += textMaxSize + intervalX;
  //繪製分數
  //設置字體
  // context.font = Math.floor(fontSize * 4/5) + "px Arial";
  context.fillText(data.kgscore + "", x+20, startY + i * preOffsetY + textOffsetY, textMaxSize);
}

/**
 * 根據傳入的buttonKey 執行點擊處理
 * 0 爲上一頁按鈕
 * 1 爲下一頁按鈕
 */
function buttonClick(buttonKey) {
  let old_buttonY;
  if (buttonKey == 0) {
    page--;
    if (page < 0){
      page = 0;
    }
    renderDirty = true;
    // console.log('上一頁' + page);
    setTimeout(() => {
      //重新渲染必須標髒
      renderDirty = true;
    }, 100);
  } else if (buttonKey == 1) {
    page++;
    let maxPage = Math.ceil(totalGroup.length / perPageMaxNum);
    // console.log("maxPage = ",maxPage,", page = ",page ,", per = ",perPageMaxNum);
    if (page >= maxPage ){
      page = maxPage-1;
      if (page < 0){
        page = 0;
      }
    } 

    renderDirty = true;
    // console.log('下一頁' + page);
    setTimeout(() => {
      // nextButtonY = old_buttonY;
      //重新渲染必須標髒
      renderDirty = true;
    }, 100);
  }

}

/////////////////////////////////////////////////////////////////// 相關緩存數據

///////////////////////////////////數據相關/////////////////////////////////////

/**
 * 渲染標髒量
 * 會在被標髒(true)後重新渲染
 */
let renderDirty = true;

/**
 * 當前繪製組
 */
let currentGroup = [];
/**
 * 每頁最多顯示個數
 */
let perPageMaxNum = 7;
/**
 * 當前頁數,默認0爲第一頁
 */
let page = 0;
///////////////////////////////////繪製相關///////////////////////////////
/**
 * 舞臺大小
 */
let stageWidth;
let stageHeight;
/**
 * 排行榜大小
 */
let rankWidth;
let rankHeight;

/**
 * 每個頭像條目的大小
 */
let barWidth;
let barHeight;
/**
 * 條目與排行榜邊界的水平距離
 */
let offsetX_barToRank
/**
 * 繪製排行榜起始點X
 */
let startX;
/**
 * 繪製排行榜起始點Y
 */
let startY;
/**
 * 每行Y軸間隔offsetY
 */
let preOffsetY;

/**
 * 字體大小
 */
let fontSize;
/**
 * 文本文字Y軸偏移量
 * 可以使文本相對於圖片大小居中
 */
let textOffsetY;
/**
 * 頭像大小
 */
let avatarSize;
/**
 * 名字文本最大寬度,名稱會根據
 */
let textMaxSize;
/**
 * 繪製元素之間的間隔量
 */
let intervalX;
/**
 * 排行榜與舞臺邊界的水平距離
 */
let offsetX_rankToBorder;
/**
 * 排行榜與舞臺邊界的豎直距離
 */
let offsetY_rankToBorder;
/**
 * 繪製排名的最大寬度
 */
let indexWidth;


/**
 * 是否加載過資源的標記量
 */
let hasLoadRes;

/**
 * 資源加載
 */
function preloadAssets() {
  // console.log("preloadAssets");
  let preloaded = 0;
  let count = 0;
  for (let asset in assetsUrl) {
    count++;
    const img = wx.createImage();
    img.onload = () => {
      preloaded++;
      if (preloaded == count) {
        // console.log("加載完成");
        hasLoadRes = true;
      }

    }
    img.src = assetsUrl[asset];
    assets[asset] = img;
  }
}


/**
 * 繪製屏幕
 * 這個函數會在加載完所有資源之後被調用
 */
function createScene() {
  if (sharedCanvas.width && sharedCanvas.height) {
    stageWidth = sharedCanvas.width;
    stageHeight = sharedCanvas.height;
    // console.log('createScene ',stageWidth,stageHeight);
    init();
    return true;
  } else {
    console.log('創建開放數據域失敗,請檢查是否加載開放數據域資源');
    return false;
  }
}


//記錄requestAnimationFrame的ID
let requestAnimationFrameID = null;
let hasCreateScene;

let isJiesuan = false;
/**
 * 增加來自主域的監聽函數
 */
function addOpenDataContextListener() {
  console.log('增加監聽函數')
  wx.onMessage((data) => {
    // console.log(data);
    if (data.command === "open_jiesuan"){
      isJiesuan = true;
      // if (!hasCreateScene) {
        //創建並初始化
        hasCreateScene = createScene();
      // }else{
      //   console.error("already have createScene");
      // }
      
      perPageMaxNum = 3;
      initParams();
      requestAnimationFrameID = requestAnimationFrame(loop);
      refreshRank();

    }else if (data.command == 'open') {
      isJiesuan = false;

      // if (!hasCreateScene) {
        //創建並初始化
        hasCreateScene = createScene();
      // }else{
      //   console.error("already have createScene");
      // }

      perPageMaxNum = 7;
      initParams();
      requestAnimationFrameID = requestAnimationFrame(loop);
      refreshRank();
    } else if (data.command == 'close' && requestAnimationFrameID) {
      cancelAnimationFrame(requestAnimationFrameID);
      requestAnimationFrameID = null
    } else if (data.command == 'loadRes' && !hasLoadRes) {
      preloadAssets();
    }else if (data.command === 'last') {
      // console.log("click last");
      buttonClick(0);
    }else if (data.command === 'next') {
      // console.log("click next");
      buttonClick(1);
    }else if (data.command === 'updateRankDatas') {
      let openContext = wx.getSharedCanvas().getContext("2d");
      openContext["canvas"]["userDataList"] = JSON.stringify(userDataList);
    }else if (data.command === 'saveInfo'){
      // wx.removeUserCloudStorage({
      //   keyList:["time","score","name","now"],
      //   success:function(data){
      //       console.log("remove data = ",JSON.stringify(data));
      //   }
      // });
      // console.log("begin saveInfo data = ",JSON.stringify(data));

      wx.setUserCloudStorage({
        KVDataList: [
          {key:"kgsec",value:data["kgsec"]},
          {key:"kgscore",value:String(data["kgscore"])},
          {key:"kgname",value:data["kgname"]}
        ],
        success: ()=>{
          // console.log("saveInfo data = ",JSON.stringify(data));
          refreshRank();
        }
      });
    }
  });
}

function refreshRank(){
  wx.getUserCloudStorage({
    keyList: ["kgsec","kgscore","kgname"],
    success: function (data) {
      //獲取玩家數據成功
      // console.log("getData ",JSON.stringify(data));
      refreshFriend();
    }
  });
}

function refreshFriend(){
  wx.getFriendCloudStorage({
    keyList:["kgscore","kgsec"],
    success:function(res){
      let data = res.data;
      totalGroup.splice(0,totalGroup.length);
      // console.log("refreshFriend: ",totalGroup.length,", ",JSON.stringify(data));
      for (let i = 0; i< data.length; i++){
        let userData = data[i];
        let openid = userData.openid;
        let nickname  = userData.nickname;
        let avatarUrl = userData.avatarUrl;
        let dList = userData.KVDataList;
        let kgscore = 0;
        let kgsec = null;
        
        for (let kv of dList){
          let k = kv["key"];
          let v = kv["value"];
          if (k ==="kgscore"){
            kgscore = v;
            // kgscore = String(Math.floor(Math.random() * (5422 - 5 + 1) + 5));
          }else if (k === "kgsec"){
            kgsec = v;
          }
        }

        let db ={    
          key: i+1,
          nickname: nickname,
          avatarUrl:avatarUrl,
          icon: assets.icon,
          kgscore: kgscore,
          kgsec: kgsec,
          openid: openid
        } 

        totalGroup.push(db);
      }

      totalGroup.sort(function(last,next){
          let sScore = Number(last.kgscore);
          let eScore = Number(next.kgscore);
          if (sScore > eScore){
            return -1;
          }
          return 1;
      });

      for (let n = 0; n < totalGroup.length; n++){
        totalGroup[n]["key"] = n+1;
      }

      // console.log("refreshFriend: totalGroup", JSON.stringify(totalGroup));
      renderDirty = true;
    }
  });
}

addOpenDataContextListener();

/**
 * 循環函數
 * 每幀判斷一下是否需要渲染
 * 如果被標髒,則重新渲染
 */
function loop() {
  if (renderDirty) {
    // console.log(`stageWidth :${stageWidth}   stageHeight:${stageHeight}`)
    context.setTransform(1, 0, 0, 1, 0, 0);

    context.clearRect(0, 0, sharedCanvas.width, sharedCanvas.height);
    drawRankPanel();
    renderDirty = false;
  }
  requestAnimationFrameID = requestAnimationFrame(loop);
}

/**
 * 圖片繪製函數
 */
function context_drawImage(image, x, y, width, height) {
  if (image.width != 0 && image.height != 0 && context) {
    if (width && height) {
      context.drawImage(image, x, y, width, height);
    } else {
      context.drawImage(image, x, y);
    }
  }
}

在主工程中通過postmessage控制排行榜翻頁


    public isRankClick: boolean = false;
    private rankBitmap: egret.Bitmap = null;
    private rankingGroup: eui.Group;
    private btnRankBack: egret.Bitmap = null;

    public openRank() {

        //處理遮罩,避免開放域數據影響主域

        this.rankingGroup = new eui.Group();
        this.rankingGroup.x = 0;
        this.rankingGroup.y = 0;
        this.rankingGroup.width = this.stage.width;
        this.rankingGroup.height = this.stage.height;

        this.rankingGroup.touchEnabled = false;
        this.rankingGroup.touchChildren = true;
        this.addChildAt(this.rankingGroup, 999);

        let blackMaskRect = new eui.Rect();
        blackMaskRect.x = 0;
        blackMaskRect.y = 0;
        blackMaskRect.width = this.stage.width;
        blackMaskRect.height = this.stage.height;
        blackMaskRect.fillColor = 0x000000;
        blackMaskRect.alpha = 0.7;
        blackMaskRect.touchEnabled = true;
        this.rankingGroup.addChild(blackMaskRect);

        let bgBlueRect: eui.Rect = new eui.Rect();
        bgBlueRect.width = 660;
        bgBlueRect.height = 1024;
        bgBlueRect.x = 30;
        bgBlueRect.y = 188;
        bgBlueRect.fillColor = 0x3db7c5;
        this.rankingGroup.addChild(bgBlueRect);

        let titleBg: eui.Image = new eui.Image();
        titleBg.texture = RES.getRes(ResImgDefine.paihangbang_bg_png);
        titleBg.x = 36;
        titleBg.y = 212;
        titleBg.width = 653;
        titleBg.height = 986;
        this.rankingGroup.addChild(titleBg);

        let titleImg: eui.Image = new eui.Image();
        titleImg.texture = RES.getRes(ResImgDefine.paihangbang_title_png);
        titleImg.x = 102;
        titleImg.y = 162;
        this.rankingGroup.addChild(titleImg);

        let titleName: eui.Label = new eui.Label();
        titleName.$setText("好友排行");
        titleName.$setSize(65);
        titleName.$setTextColor(0xfffdef);
        titleName.$setStrokeColor(0xb05539);
        titleName.$setStrokeColor(3);
        titleName.x = 236;
        titleName.y = 172;
        titleName.bold = true;
        this.rankingGroup.addChild(titleName);

        let everyWeekTxt: eui.Label = new eui.Label();
        everyWeekTxt.$setText("排行榜每週一刷新");
        everyWeekTxt.$setSize(28);
        everyWeekTxt.$setTextColor(0xe77364);
        everyWeekTxt.x = 402;
        everyWeekTxt.y = 1134;
        everyWeekTxt.bold = true;
        this.rankingGroup.addChild(everyWeekTxt);

        let lineGroup: eui.Rect = new eui.Rect();
        lineGroup.width = 595;//585;
        lineGroup.height = 785;//109;
        lineGroup.x = (GDatas.getStageWidth() - lineGroup.width) / 2;//70;
        lineGroup.y = 277;
        // lineGroup.fillColor = 0x00ff00;
        lineGroup.fillAlpha = 0;
        this.rankingGroup.addChild(lineGroup);


        if (!this.btnRankBack) {
            this.btnRankBack = new egret.Bitmap();
            this.btnRankBack.texture = RES.getRes(ResImgDefine.btn_back_png);
        }

        this.btnRankBack.touchEnabled = true;
        this.rankingGroup.addChild(this.btnRankBack);
        this.btnRankBack.x = 52;
        this.btnRankBack.y = 71;
        this.btnRankBack.addEventListener(egret.TouchEvent.TOUCH_TAP, (event: egret.TouchEvent) => {
            // this.closeRank();
        }, this);

        //顯示開放域數據
        let xInterval: number = 70;
        let texture: egret.Texture = RES.getRes(ResImgDefine.btn_ok_png);
        let lastGroup: eui.Group = new eui.Group();
        lastGroup.width = texture.$bitmapWidth / 2;
        lastGroup.height = texture.$bitmapHeight / 2;
        lastGroup.x = lineGroup.x + xInterval;
        lastGroup.y = lineGroup.y + lineGroup.height + 4;
        lastGroup.touchEnabled = true;
        lastGroup.touchChildren = false;
        lastGroup.addEventListener(egret.TouchEvent.TOUCH_TAP, (event: egret.TouchEvent) => {
            egret.log("btnLast");
            if (GDatas.platformType === EPlatformType.wx) {
                platform.openDataContext.postMessage({
                    isRanking: this.isRankClick,
                    text: "egret",
                    year: (new Date()).getFullYear(),
                    command: "last"
                });
            }
        }, this);
        this.rankingGroup.addChild(lastGroup);

        let btnLast: egret.Bitmap = new egret.Bitmap();
        btnLast.texture = RES.getRes(ResImgDefine.btn_ok_png);
        btnLast.touchEnabled = true;
        btnLast.x = 0;
        btnLast.y = 0;
        btnLast.scaleX = 1 / 2;
        btnLast.scaleY = 1 / 2;
        lastGroup.addChild(btnLast);


        let txtLast: eui.Label = new eui.Label();
        txtLast.$setText("上一頁");
        txtLast.$setSize(24);
        txtLast.$setTextColor(0x000001);
        txtLast.$setStrokeColor(0x000001);
        txtLast.$setStrokeColor(2);
        txtLast.textAlign = egret.HorizontalAlign.CENTER;
        txtLast.verticalAlign = egret.VerticalAlign.MIDDLE;
        txtLast.width = btnLast.width * btnLast.scaleX;
        txtLast.height = btnLast.height * btnLast.scaleY;
        txtLast.x = btnLast.x;
        txtLast.y = btnLast.y;
        txtLast.bold = true;
        txtLast.touchEnabled = false;
        lastGroup.addChild(txtLast);


        let nextGroup: eui.Group = new eui.Group();
        nextGroup.width = texture.$bitmapWidth / 2;
        nextGroup.height = texture.$bitmapHeight / 2;
        nextGroup.x = lineGroup.x + lineGroup.width - nextGroup.width - xInterval;
        nextGroup.y = lastGroup.y;
        nextGroup.touchEnabled = true;
        nextGroup.touchChildren = false;
        nextGroup.addEventListener(egret.TouchEvent.TOUCH_TAP, (event: egret.TouchEvent) => {
            egret.log("btnNext");
            if (GDatas.platformType === EPlatformType.wx) {
                platform.openDataContext.postMessage({
                    isRanking: this.isRankClick,
                    text: "egret",
                    year: (new Date()).getFullYear(),
                    command: "next"
                });
            }
        }, this);
        this.rankingGroup.addChild(nextGroup);

        let btnNext: egret.Bitmap = new egret.Bitmap();
        btnNext.texture = RES.getRes(ResImgDefine.btn_ok_png);
        btnNext.touchEnabled = true;
        btnNext.x = 0;
        btnNext.y = 0;
        btnNext.scaleX = 1 / 2;
        btnNext.scaleY = 1 / 2;

        nextGroup.addChild(btnNext);
        egret.log("btnLast.width1 = ", btnLast.width, RES.getRes(ResImgDefine.btn_ok_png));

        let txtNext: eui.Label = new eui.Label();
        txtNext.$setText("下一頁");
        txtNext.$setSize(24);
        txtNext.$setTextColor(0x000001);
        txtNext.$setStrokeColor(0x000001);
        txtNext.$setStrokeColor(2);
        txtNext.textAlign = egret.HorizontalAlign.CENTER;
        txtNext.verticalAlign = egret.VerticalAlign.MIDDLE;
        txtNext.width = btnNext.width * btnNext.scaleX;
        txtNext.height = btnNext.height * btnNext.scaleY;
        txtNext.x = btnNext.x;
        txtNext.y = btnNext.y;
        txtNext.bold = true;
        nextGroup.addChild(txtNext);

        this.isRankClick = true;

        if (GDatas.platformType === EPlatformType.wx) {
            // this.bitmap = platform.openDataContext.createDisplayObject(null, this.stage.stageWidth, this.stage.stageHeight);
            this.rankBitmap = platform.openDataContext.createDisplayObject(null, lineGroup.width, lineGroup.height);
            lineGroup.touchEnabled = false;
            lineGroup.touchChildren = true;
            lineGroup.addChild(this.rankBitmap);
            //主域向子域發送數據
            platform.openDataContext.postMessage({
                isRanking: this.isRankClick,
                text: "egret",
                year: (new Date()).getFullYear(),
                command: "open"
            });

            //TODO: 
            let date = new Date();
            let clock: string = String(date.getMinutes()) + "-" + String(date.getSeconds());
            platform.openDataContext.postMessage({
                command: 'saveInfo',
                kgsec: clock,
                kgscore: 8745,
                kgname: "hello"
            });

        }
    }

用eui做底

class MNUiWxTestContainer extends eui.Component {
    //從exml的UI配置中讀出的屬性
    public _btnBack: eui.Image;
    public _labelCurrentGold: eui.Label;
    public _labelTargetGold: eui.Label;
    public _listGroup:eui.Group;
    public _btnShareGroup:eui.Group;

    private status: EPlayerStatus = EPlayerStatus.idle;

    private currentGold: number = 0;
    private targetGold: number = 0;

    private rankBitmap: egret.Bitmap = null;

    public constructor() {
        super();
        this.skinName = "resource/eui_skins/skins/miner/JiesuanSkin.exml";
    }

    public init() {

        this.currentGold = 10;
        this.targetGold = 888;

        GDatas.pushGold(this.currentGold);
        
        egret.callLater(() => {
            this._labelCurrentGold.type = DefaultDefine.TextInputForbid;
            this._labelCurrentGold.type = DefaultDefine.TextInputForbid;
            this._labelTargetGold.type = DefaultDefine.TextInputForbid;
            this._labelTargetGold.type = DefaultDefine.TextInputForbid;
            this.refreshGold();

            this._btnBack.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouchDown, this);
            this._btnBack.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouchDown, this);

            this._btnShareGroup.touchChildren = false;
            this._btnShareGroup.touchEnabled = true;
            this._btnShareGroup.removeEventListener(egret.TouchEvent.TOUCH_TAP,this.onTouchDown,this);
            this._btnShareGroup.addEventListener(egret.TouchEvent.TOUCH_TAP,this.onTouchDown,this);

            this.createRank();


        }, this);
    }

    public onTouchDown(event: egret.TouchEvent) {
        event.stopPropagation();

        if (event.target === this._btnBack) {
            this.exit();
        }else if (event.target === this._btnShareGroup){
            this.share();
        }
    }

    private async share() {
        await platform.shareAppMessage().then(() => {
            this.coinFly(2);
            this.exit();
        }).catch(() => {
            egret.error("share: 分享失敗");
            return;
        });
    }

    public createRank(){
        this._listGroup.removeChildren();
        if (GDatas.platformType === EPlatformType.wx) {
            this.rankBitmap = platform.openDataContext.createDisplayObject(null, this._listGroup.width, this._listGroup.height);
            this._listGroup.touchEnabled = false;
            this._listGroup.touchChildren = true;
            this._listGroup.addChild(this.rankBitmap);
            //主域向子域發送數據
            platform.openDataContext.postMessage({
                text: "egret",
                year: (new Date()).getFullYear(),
                command: "open_jiesuan"
            });
        }
    }

    public exit() {
        App.DisplayUtils.removeFromParent(this);

        SaveData.getInstance().setNumByKey(SaveData.keyFail, 0);
        let toolNames: string[] = GDatas.getToolNames();

        for (let name of toolNames) {
            let itKey: string = SaveData.getInstance().getKeyChuang(name);
            SaveData.getInstance().setNumByKey(itKey, 0);
        }
    }

    public refreshGold() {
        this._labelCurrentGold.type = DefaultDefine.TextInputForbid;
        this._labelCurrentGold.$setText(String(this.currentGold));

        this._labelTargetGold.type = DefaultDefine.TextInputForbid;
        this._labelTargetGold.type = DefaultDefine.TextInputForbid;
        this._labelTargetGold.$setText(String(this.targetGold));
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章