unity开发webGL,引用js功能。

读写Excel参考连接
打开本地文件参考连接
对JS一点不懂,记录一下开发中用到的调用JS代码,方便以后查找。
包含了调用MQTT和读写Excel功能。

DOCTYPE html>
<html lang="en-us">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Unity WebGL Player | {{{ PRODUCT_NAME }}}title>
    <link rel="shortcut icon" href="TemplateData/favicon.ico">
    <link rel="stylesheet" href="TemplateData/style.css">
  head>
  <body>
    <div id="unity-container" class="unity-desktop"
	style="width: 100%; height: 100%; margin: auto">
      <canvas id="unity-canvas"
	  style="width: 100%; height: 100%; margin: auto">canvas>
      <div id="unity-loading-bar">
        <div id="unity-logo">div>
        <div id="unity-progress-bar-empty">
          <div id="unity-progress-bar-full">div>
        div>
      div>
    div>
	<script src="Build/MyMqtt.js">script>//引用的js文件,添加后可以直接使用里边的方法
	<script src="Build/xlsx.full.min.js">script>
    <script>
      var buildUrl = "Build";
      var loaderUrl = buildUrl + "/{{{ LOADER_FILENAME }}}";
      var config = {
        dataUrl: buildUrl + "/{{{ DATA_FILENAME }}}",
        frameworkUrl: buildUrl + "/{{{ FRAMEWORK_FILENAME }}}",
        codeUrl: buildUrl + "/{{{ CODE_FILENAME }}}",
#if MEMORY_FILENAME
        memoryUrl: buildUrl + "/{{{ MEMORY_FILENAME }}}",
#endif
#if SYMBOLS_FILENAME
        symbolsUrl: buildUrl + "/{{{ SYMBOLS_FILENAME }}}",
#endif
        streamingAssetsUrl: "StreamingAssets",
        companyName: "{{{ COMPANY_NAME }}}",
        productName: "{{{ PRODUCT_NAME }}}",
        productVersion: "{{{ PRODUCT_VERSION }}}",
      };

      var container = document.querySelector("#unity-container");
      var canvas = document.querySelector("#unity-canvas");
      var loadingBar = document.querySelector("#unity-loading-bar");
      var progressBarFull = document.querySelector("#unity-progress-bar-full");
      var fullscreenButton = document.querySelector("#unity-fullscreen-button");

      if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
        container.className = "unity-mobile";
        config.devicePixelRatio = 1;
      }
      loadingBar.style.display = "block";
	  var gameInstance;
      var script = document.createElement("script");
      script.src = loaderUrl;
      script.onload = () => {
        createUnityInstance(canvas, config, (progress) => {
          progressBarFull.style.width = 109 * progress + "%";
        }).then((unityInstance) => {
          loadingBar.style.display = "none";
          gameInstance=unityInstance;
        });
      };
      document.body.appendChild(script);
        function JsToUnityString(content) {
            //console.log(content);
            gameInstance.SendMessage("WebToUnity", "JsToUnity", content);
        }
		
        window.addEventListener("message", (e) => {
        //console.log(e.data);
        JsToUnityString(e.data);
      });
        var mqttClient;
        var wsUrl ='ws://localhost:8083/mqtt';
        var subNameReceive = '';
        function MQTTConnect() {
            const options = {
                clean: true, // true: 清除会话, false: 保留会话
                connectTimeout: 4000, // 超时时间
                // 认证信息
                //clientId: 'test',	//客户端ID
                username: 'admin', //连接用户名
                password: 'password',//连接密码,有的密码默认为public
                // 心跳时间
                keepalive: 60,
				//Qos: 2,
            }

            mqttClient = mqtt.connect(wsUrl, options);
            mqttClient.on('connect', function () {
                //console.log('Connected Succeed')
                gameInstance.SendMessage("WebToUnity", "MQTTConnectSucceed");
                MQTTSubscribe(subNameReceive);
				
            })
            //失败重连
            mqttClient.on('reconnect', (error) => {
                //console.log('正在重连:', error)
                gameInstance.SendMessage("WebToUnity", "MQTTReConnect");
            })
            //连接失败
            mqttClient.on('error', (error) => {
                console.log('连接失败:', error)
                gameInstance.SendMessage("WebToUnity", "MQTTConnectFail");
            })
            //接受消息
            mqttClient.on('message', function (topic, message) {
                // message is Buffer
                //console.log("subNmae=" + topic.toString())
                //console.log("msg=" + message.toString())
                //mqttClient.end()
				if(topic==subNameReceive)
				{
					JsToUnityString(message.toString());
				}         
            })
        }
        //订阅
        function MQTTSubscribe(subNameReceive) {
            mqttClient.subscribe(subNameReceive, function (err) {
                if (!err) {
                    gameInstance.SendMessage("WebToUnity", "MQTTSubscribeResult", 1);
                }
                else {
                    gameInstance.SendMessage("WebToUnity", "MQTTSubscribeResult", 0);
                }
            })
        }
        //发布
        function MQTTPublish(subNameSend,content) {
            mqttClient.publish(subNameSend, content);
        }
        //关闭
        function MQTTClosed() {
            mqttClient.end();
        }


        function SetDebug() {
            return 1//设置是否显示debug信息,0=显示,1=不显示
        }
		//打开资源管理器选择文件
		function clickSelectFileBtn() {
		var tempFileLayout = document.getElementById('files');
        tempFileLayout.click();
		}
		//加载excel文件内容,发送给Unity
		function fileImport() {
		//获取读取文件的File对象		
        var selectedFile = document.getElementById('files').files[0];
        if (selectedFile != null) {
		var reader = new FileReader();
			reader.readAsBinaryString(selectedFile);
		reader.onload = function(e) {
		var data = e.target.result;
		var workbook = XLSX.read(data, {type: 'binary'});
	    var sheetNames = workbook.SheetNames; // 工作表名称集合
	    var worksheet = workbook.Sheets[sheetNames[0]]; // 这里我们只读取第一张sheet
	    var csv = XLSX.utils.sheet_to_csv(worksheet);
	    //console.log(csv);
	    var sendContent={"msgType":"openFile","data":csv};
	    JsToUnityString(window.JSON.stringify(sendContent));	
	};
		}
     	}
	  // 传入csv,执行后就会弹出下载框
	function exportExcel(csv) 
	{
		var csvobj = window.JSON.parse(newStr);
		var sheet = XLSX.utils.json_to_sheet(csvobj);
		openDownloadDialog(sheet2blob(sheet), '导出.xlsx');
	}
	  
	  /**
 * 通用的打开下载对话框方法,没有测试过具体兼容性
 * @param url 下载地址,也可以是一个blob对象,必选
 * @param saveName 保存文件名,可选
 */
function openDownloadDialog(url, saveName)
{
	if(typeof url == 'object' && url instanceof Blob)
	{
		url = URL.createObjectURL(url); // 创建blob地址
	}
	var aLink = document.createElement('a');
	aLink.href = url;
	aLink.download = saveName || ''; // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效
	var event;
	if(window.MouseEvent) event = new MouseEvent('click');
	else
	{
		event = document.createEvent('MouseEvents');
		event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
	}
	aLink.dispatchEvent(event);
	if(typeof url == 'object' && url instanceof Blob)
	{
		URL.revokeObjectURL(url);
	}
}

// 将一个sheet转成最终的excel文件的blob对象,然后利用URL.createObjectURL下载
function sheet2blob(sheet, sheetName) {
	sheetName = sheetName || 'sheet1';
	var workbook = {
		SheetNames: [sheetName],
		Sheets: {}
	};
	workbook.Sheets[sheetName] = sheet;
	// 生成excel的配置项
	var wopts = {
		bookType: 'xlsx', // 要生成的文件类型
		bookSST: false, // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性
		type: 'binary'
	};
	var wbout = XLSX.write(workbook, wopts);
	var blob = new Blob([s2ab(wbout)], {type:"application/vnd.ms-excel"});
	// 字符串转ArrayBuffer
	function s2ab(s) {
		var buf = new ArrayBuffer(s.length);
		var view = new Uint8Array(buf);
		for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
		return buf;
	}
	return blob;
}
    script>
	<input type="file" id="files" style="display:none" onchange="fileImport()">//打开文件按钮,设置为隐藏,只使用功能。
  body>
html>

你可能感兴趣的:(问题记录,unity,webgl)