加载图片数据,以及设置开放域画布的宽高
2018-11-06 本文已影响0人
广州芦苇科技web前端
作者: 何永峰;
标签: 微信小游戏,开放域
加载图片数据,以及初步绘制canvas
加载图片数据
之前我们有提到过主域通过postMessage的API向子域发送消息
我们利用这个也可以提醒开放域及时加载资源
当我们主域已经加载好游戏的时候,可以向开放域中发送消息,提醒加载图片数据
然后在开放域中的onMessage方法中接收到要加载图片的时候调用下面方法
//开放域的index.js
const assetsUrl = {
panel: "openDataContext/assets/bg_popup.png",
buttonLetf: "openDataContext/assets/btn_lastpage.png",
buttonRight: "openDataContext/assets/btn_nextpage.png",
add:"openDataContext/assets/btn_friend_add.png"
};
/**
* 是否加载过资源的标记量
*/
let assets = {};
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;
}
}
配置开放域的大小
//主域
public linkOpenData(message: {}, width?: number, height?: number, data?: Object) {
console.log('调用开放数据域')
let basic = {
isRanking: false,
text: "egret",
data: data,
year: (new Date()).getFullYear(),
command: "open"
}
for (let key in message) {
basic[key] = message[key];
}
let open_data_container = new egret.Sprite();
let openDataContext = wx.getOpenDataContext();
const bitmapdata = new egret.BitmapData(window["sharedCanvas"]);
bitmapdata.$deleteSource = false;
const texture = new egret.Texture();
texture._setBitmapData(bitmapdata);
let bitmap: egret.Bitmap;
bitmap = new egret.Bitmap(texture);
bitmap.width = width || GameConfig.getWidth();
bitmap.height = height || GameConfig.getHeight();
bitmap.name = "openData";
open_data_container.addChild(bitmap);
console.log(bitmap.width + ' ' + bitmap.height)
egret.startTick((timeStarmp: number) => {
egret.WebGLUtils.deleteWebGLTexture(bitmapdata.webGLTexture);
bitmapdata.webGLTexture = null;
return false;
}, this);
openDataContext.postMessage(basic);
console.log('link_done');
return open_data_container;
}
//再加上简单的三句代码就能把开放域显示在游戏上
let openDataContext = this.linkOpenData({},"这里传宽度","这里传高度");
this.openDataContext = openDataContext;
this.addChild(openDataContext)
获取主域传过来的宽高
//index.js
//先根据API,获取离屏画布
context = sharedCanvas.getContext("2d");
context.globalCompositeOperation = "source-over";
//然后在开放域接受宽高的方式
yfwidth = sharedCanvas.width;
yfheight = sharedCanvas.height;
//你就可以根据这个宽高来做适配