二 .白鹭小游戏接微信排行榜(2)

接着上一篇:.白鹭小游戏接微信排行榜(1)开始说;

1.首先大家先要明白俩个概念;

(1).开放域

(2).主域

这俩概念随便百度都有的;

   ZZ: 这里博主白话说一下,开放域是微信为了保护微信用户隐私,所出现的概念;因为我们开放小游戏等;必须拉起微信自己的信息,包括好友的信息等;所以,微信对很多功能,只提供在开放域【微信帮我们生成的index.js那个脚本里面】操作,不提供在其他地方主域【白鹭自己写的Typescript类等脚本里面】操作;

2.给开放域发消息

为了让微信开发者,可以通知开放域里面的某某代码执行做一些事情,所以开放域提供了postMessage()这个方法来,让开发者给开放域【index.js】这个脚本发消息,然后执行对应操作;

发送方式是主域定义在platform里面的openDatacontext.postMessage(

  {
   key:'value'//童鞋们:key可以自己随便定义的,value也一样;可以一次性传很多key value过去;

//[只要你在开放域在对应的接受消息方法里面,把对应的key值都给填上去,自己做响应就行了];
   }

);

这样,就可以给开放域发消息了;注意:开放域目前不可以发消息给主域,这也是微信对用户信息的,一种保护机制;

3.熟悉index.js(开放域)脚本的关键函数;

打开自己对应项目的微信开发者工具,展开其如下目录;

点击index.js查看,点击清缓存下面的[]<-这图标 收起目录界面【可以让界面更大点】;

下面为白鹭发布到微信工具那边,自动帮你生成的index.js[开放域]脚本;

【童鞋们看一下,这个自动生成的index.js他基本每个地方都有注释了;~ o(* ̄▽ ̄*)o】

我们接下来的操作就是把这里的东西熟悉,规整一下后,然后接入自己的微信排行榜;

/**
 * 微信开放数据域
 * 使用 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进行计算
 */
const totalGroup = [{
    key: 1,
    name: "1111111111",
    url: assets.icon,
    scroes: 10000
  },
  {
    key: 2,
    name: "2222222222",
    url: assets.icon,
    scroes: 9000
  },
  {
    key: 3,
    name: "3333333",
    url: assets.icon,
    scroes: 8000
  },
  {
    key: 4,
    name: "4444444",
    url: assets.icon,
    scroes: 7000
  },
  {
    key: 5,
    name: "55555555",
    url: assets.icon,
    scroes: 6000
  },
  {
    key: 6,
    name: "6666666",
    url: assets.icon,
    scroes: 5000
  },
  {
    key: 7,
    name: "7777777",
    url: assets.icon,
    scroes: 4000
  },
  {
    key: 8,
    name: "8888888",
    url: assets.icon,
    scroes: 3000
  },
  {
    key: 9,
    name: "9999999",
    url: assets.icon,
    scroes: 2000
  },
  {
    key: 10,
    name: "1010101010",
    url: assets.icon,
    scroes: 2000
  },
  {
    key: 11,
    name: "111111111111",
    url: assets.icon,
    scroes: 2000
  },
  {
    key: 12,
    name: "121212121212",
    url: assets.icon,
    scroes: 2000
  },
  {
    key: 13,
    name: "13131313",
    url: assets.icon,
    scroes: 2000
  },
  {
    key: 14,
    name: "1414141414",
    url: assets.icon,
    scroes: 2000
  },
  {
    key: 15,
    name: "1515151515",
    url: assets.icon,
    scroes: 2000
  },
  {
    key: 16,
    name: "1616161616",
    url: assets.icon,
    scroes: 2000
  },
];

/**
 * 创建排行榜
 */
function drawRankPanel() {
  //绘制背景
  context_drawImage(assets.panel, offsetX_rankToBorder, offsetY_rankToBorder, rankWidth, rankHeight);
  //绘制标题
  const title = assets.title;
  //根据title的宽高计算一下位置;
  const titleX = offsetX_rankToBorder + (rankWidth - title.width) / 2;
  const titleY = offsetY_rankToBorder + title.height + 40;
  context_drawImage(title, titleX, titleY);
  //获取当前要渲染的数据组

  //起始id
  const startID = perPageMaxNum * page;
  currentGroup = totalGroup.slice(startID, startID + perPageMaxNum);
  //创建头像Bar
  drawRankByGroup(currentGroup);
  //创建按钮
  drawButton()
}
/**
 * 根据屏幕大小初始化所有绘制数据
 */
function init() {
  //排行榜绘制数据初始化,可以在此处进行修改
  rankWidth = stageWidth * 4 / 5;
  rankHeight = stageHeight * 4 / 5;
  barWidth = rankWidth * 4 / 5;
  barHeight = rankWidth / perPageMaxNum;
  offsetX_rankToBorder = (stageWidth - rankWidth) / 2;
  offsetY_rankToBorder = (stageHeight - rankHeight) / 2;
  preOffsetY = (rankHeight - barHeight) / (perPageMaxNum + 1);
  fontSize = Math.floor(stageWidth / 25);
  startX = offsetX_rankToBorder + (rankWidth - barWidth) / 2;
  startY = offsetY_rankToBorder + preOffsetY;
  avatarSize = barHeight - 10;
  intervalX = barWidth / 20;
  textOffsetY = (barHeight + fontSize) / 2;
  textMaxSize = barWidth / 3;
  indexWidth = context.measureText("99").width;

  //按钮绘制数据初始化
  buttonWidth = barWidth / 3;
  buttonHeight = barHeight / 2;
  buttonOffset = rankWidth / 3;
  lastButtonX = offsetX_rankToBorder + buttonOffset - buttonWidth;
  nextButtonX = offsetX_rankToBorder + 2 * buttonOffset;
  nextButtonY = lastButtonY = offsetY_rankToBorder + rankHeight - 50 - buttonHeight;
  let data = wx.getSystemInfoSync();
  canvasWidth = data.windowWidth;
  canvasHeight = data.windowHeight;
}

/**
 * 创建两个点击按钮
 */
function drawButton() {
  context_drawImage(assets.button, nextButtonX, nextButtonY, buttonWidth, buttonHeight);
  context_drawImage(assets.button, lastButtonX, lastButtonY, buttonWidth, buttonHeight);
}


/**
 * 根据当前绘制组绘制排行榜
 */
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;
  //绘制底框
  context_drawImage(assets.box, startX, startY + i * preOffsetY, barWidth, barHeight);
  x += 10;
  //设置字体
  context.font = fontSize + "px Arial";
  //绘制序号
  context.fillText(data.key + "", x, startY + i * preOffsetY + textOffsetY, textMaxSize);
  x += indexWidth + intervalX;
  //绘制头像
  context_drawImage(assets.icon, x, startY + i * preOffsetY + (barHeight - avatarSize) / 2, avatarSize, avatarSize);
  x += avatarSize + intervalX;
  //绘制名称
  context.fillText(data.name + "", x, startY + i * preOffsetY + textOffsetY, textMaxSize);
  x += textMaxSize + intervalX;
  //绘制分数
  context.fillText(data.scroes + "", x, startY + i * preOffsetY + textOffsetY, textMaxSize);
}

/**
 * 点击处理
 */
function onTouchEnd(event) {
  let x = event.clientX * sharedCanvas.width / canvasWidth;
  let y = event.clientY * sharedCanvas.height / canvasHeight;
  if (x > lastButtonX && x < lastButtonX + buttonWidth &&
    y > lastButtonY && y < lastButtonY + buttonHeight) {
    //在last按钮的范围内
    if (page > 0) {
      buttonClick(0);

    }
  }
  if (x > nextButtonX && x < nextButtonX + buttonWidth &&
    y > nextButtonY && y < nextButtonY + buttonHeight) {
    //在next按钮的范围内
    if ((page + 1) * perPageMaxNum < totalGroup.length) {
      buttonClick(1);
    }
  }

}
/**
 * 根据传入的buttonKey 执行点击处理
 * 0 为上一页按钮
 * 1 为下一页按钮
 */
function buttonClick(buttonKey) {
  let old_buttonY;
  if (buttonKey == 0) {
    //上一页按钮
    old_buttonY = lastButtonY;
    lastButtonY += 10;
    page--;
    renderDirty = true;
    console.log('上一页' + page);
    setTimeout(() => {
      lastButtonY = old_buttonY;
      //重新渲染必须标脏
      renderDirty = true;
    }, 100);
  } else if (buttonKey == 1) {
    //下一页按钮
    old_buttonY = nextButtonY;
    nextButtonY += 10;
    page++;
    renderDirty = true;
    console.log('下一页' + page);
    setTimeout(() => {
      nextButtonY = old_buttonY;
      //重新渲染必须标脏
      renderDirty = true;
    }, 100);
  }

}

/////////////////////////////////////////////////////////////////// 相关缓存数据

///////////////////////////////////数据相关/////////////////////////////////////

/**
 * 渲染标脏量
 * 会在被标脏(true)后重新渲染
 */
let renderDirty = true;

/**
 * 当前绘制组
 */
let currentGroup = [];
/**
 * 每页最多显示个数
 */
let perPageMaxNum = 5;
/**
 * 当前页数,默认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 buttonWidth;
let buttonHeight;
/**
 * 上一页按钮X坐标
 */
let lastButtonX;
/**
 * 下一页按钮x坐标
 */
let nextButtonX;
/**
 * 上一页按钮y坐标
 */
let lastButtonY;
/**
 * 下一页按钮y坐标
 */
let nextButtonY;
/**
 * 两个按钮的间距
 */
let buttonOffset;

/**
 * 字体大小
 */
let fontSize;
/**
 * 文本文字Y轴偏移量
 * 可以使文本相对于图片大小居中
 */
let textOffsetY;
/**
 * 头像大小
 */
let avatarSize;
/**
 * 名字文本最大宽度,名称会根据
 */
let textMaxSize;
/**
 * 绘制元素之间的间隔量
 */
let intervalX;
/**
 * 排行榜与舞台边界的水平距离
 */
let offsetX_rankToBorder;
/**
 * 排行榜与舞台边界的竖直距离
 */
let offsetY_rankToBorder;
/**
 * 绘制排名的最大宽度
 */
let indexWidth;

//////////////////////////////////////////////////////////
/**
 * 监听点击
 */
wx.onTouchEnd((event) => {
  const l = event.changedTouches.length;
  for (let i = 0; i < l; i++) {
    onTouchEnd(event.changedTouches[i]);
  }
});


/**
 * 是否加载过资源的标记量
 */
let hasLoadRes;

/**
 * 资源加载
 */
function 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) {
    // console.log('初始化完成')
    stageWidth = sharedCanvas.width;
    stageHeight = sharedCanvas.height;
    init();
    return true;
  } else {
    console.log('创建开放数据域失败,请检查是否加载开放数据域资源');
    return false;
  }
}


//记录requestAnimationFrame的ID
let requestAnimationFrameID;
let hasCreateScene;

/**
 * 增加来自主域的监听函数
 */
function addOpenDataContextListener() {
  console.log('增加监听函数')
  wx.onMessage((data) => {
    console.log(data);
    if (data.command == 'open') {
      if (!hasCreateScene) {
        //创建并初始化
        hasCreateScene = createScene();
      }
      console.error('打开排行榜')
      requestAnimationFrameID = requestAnimationFrame(loop);
    } else if (data.command == 'close' && requestAnimationFrameID) {
      cancelAnimationFrame(requestAnimationFrameID);
      requestAnimationFrameID = null
    } else if (data.command == 'loadRes' && !hasLoadRes) {
      /**
       * 加载资源函数
       * 只需要加载一次
       */
       //console.error('加载资源')
      preloadAssets();
    }
  });
}

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

4.关键的函数[排行榜将用到的]

(1.)addOpenDataContextListener();这个函数为开放域接收消息的函数;

刚刚说的可以随便定义的key,童鞋们可以在这里修改,然后加上自己喜欢的key的名称;

(2.)默认的排行榜数据:为 totalGroup(json obj),里面对应的数据;

我们要做的,是把这里面的数据变成我们自己微信的数据就行了;

(3.)自己定义排行榜的背景|按钮等UI;

通过修改assetsUrl 里面的引用名称就行了【别忘记自己将对应的资源放到对应位置】;

5.提交数据|获取数据|显示数据;

(1.)设置微信排行榜数据,并提交的微信服务端;

(2.).获取自己包括好友数据,转成对应的json个数替换给totalGroup这个引用;

(3.)调用打开排行榜函数;[一切ok~ o(* ̄▽ ̄*)o] 】

[上面3项童鞋们请看下一篇博文,觉得有用的童鞋,关注支持一下~ ~ o(* ̄▽ ̄*)o]

猜你喜欢

转载自blog.csdn.net/aiwo521/article/details/83994444