egret怎么调用原生JS

JavaScript06

egret怎么调用原生JS,第1张

ts 调用 js

步骤

找到 js 调用 js 的方法。

增加方法调用的声明。 请参考 如何生成 .d.ts 。

示例

js 内的方法

function callJsFunc(msg) {

console.log("msg from egret : " + msg)

}

ts 内声明

declare function callJsFunc(msg:string)//可以放在 ts 文件内(建议在顶部或者底部,中间的没试过)或者单独放到一个 .d.ts 文件中,请不要放在其他类型的文件内。msg 类型根据函数体判断。

ts 内调用

callJsFunc("hello js")

输出

msg from egret : hello js

导入fairygui库(坑点)

将bin目录下文件保存到 项目根目录/libs/fairygui/目录下

将libs目录下文件保存到 项目根目录/libs/rawinflate/目录下

注意如果rawinflate 目录下没有rawinflate.js,则复制rawinflate.min.js保存为rawinflate.js

(egret在本地调试调用的是.js文件,如果不存在则会报错,未找到Zlib库)

在egretProperties.json文件中添加(重点)

{

"name": "rawinflate",

"path": "./libs/rawinflate"

},

{

"name": "fairygui",

"path": "./libs/fairygui"

}

测试UI案例

将导出的资源添加到resource/fairygui/目录下

修改default.res.json文件,导出的图片文件注意TankGame@atlas0命名规范

{

"groups": [

{

"keys": "TankGame,TankGame@atlas0",

"name": "preload"

}

],

"resources": [

{

"name": "TankGame",

"type": "bin",

"url": "fairygui/TankGame.fui"

},

{

"name": "TankGame@atlas0",

"type": "image",

"url": "fairygui/[email protected]"

}

]

}

修改Main.ts文件

protected startCreateScene(): void {

fairygui.UIPackage.addPackage("TankGame")

this.addChild(fairygui.GRoot.inst.displayObject)

let uiPanel = new UIPanel()

}

class UIPanel {

private root: fairygui.GComponent

public constructor() {

this.root = fairygui.UIPackage.createObject("TankGame","Main").asCom

this.root.setSize(fairygui.GRoot.inst.width,fairygui.GRoot.inst.height)

fairygui.GRoot.inst.addChild(this.root)

}

}

演示效果