WebGL平台动态修改窗口大小

1.静态设置

发布之前在Player Setting/Resolution and Presentation设置

2.动态设置

经过测试在WebGL平台打包后,Screen.SetResolution设置分辨率是不生效的

需要写js脚本

1.新建脚本WebGLResize.jslib,放在Plugins\WebGL下面

javascript 复制代码
mergeInto(LibraryManager.library, {
    ResetCanvasSize: function(width, height) {
        // 获取Unity canvas元素
        var canvas = document.querySelector("#unity-canvas");
        if (!canvas) {
            console.warn("无法找到Unity canvas元素");
            return;
        }
        
        // 设置canvas的新尺寸
        canvas.style.width = width + "px";
        canvas.style.height = height + "px";
        
        // 如果存在Unity实例,通知其resize
        if (Module) {
            Module.canvas.width = width;
            Module.canvas.height = height;
            
            // 触发Unity内部的resize事件
            if (typeof Module.onResize === 'function') {
                Module.onResize(width, height);
            }
        }
        
        // 调整容器大小(如果有父容器)
        var parent = canvas.parentElement;
        if (parent) {
            parent.style.width = width + "px";
            parent.style.height = height + "px";
        }
        
        console.log("画布已调整为: " + width + "x" + height);
    }
});

2.C#调用

完整代码:

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using TMPro;
using UnityEngine;

public class WebTest : MonoBehaviour
{
    public TextMeshProUGUI logText;

    public void Set600_960()
    {
        SetCustomCanvasSize(600, 960);
    }

    public void Set960_600()
    {
        SetCustomCanvasSize(960, 600);
    }

    public void ClearLog()
    {
        logText.text = "";
    }


#if UNITY_WEBGL && !UNITY_EDITOR
        [DllImport("__Internal")]
        private static extern void ResetCanvasSize(int width, int height);
#endif
// 设置自定义分辨率
    private void SetCustomCanvasSize(int width, int height)
    {
#if UNITY_WEBGL && !UNITY_EDITOR
            ResetCanvasSize(width, height);
#endif
        string msg = $"{width}x{height}  Screen:{Screen.width}x{Screen.height}";
        AppendLogText(msg);
        Debug.LogWarning(msg);
    }

    void AppendLogText(string msg)
    {
        logText.text = logText.text + "\n" + msg;
    }
}

3.效果展示

相关推荐
Strayer4 天前
在地图上实现管网拓扑批量移动、旋转与缩放(参考图片的实现方式)
gis·webgl·数据可视化
Strayer4 天前
WebGL 地图上做精准编辑?这套分层方案搞定管网拖拽 / 连接
gis·webgl
山海鲸可视化5 天前
数字孪生项目案例 | 物流园区可视化
webgl·可视化·数据可视化·数据表格·搜索框
图扑软件5 天前
50ms 级实时数字孪生|汽车先进制造车间工艺流程
3d·数据采集·webgl·数字孪生·可视化·opc ua·汽车制造
子兮曰6 天前
SuperSplat 深度解析:7.6K Stars 的浏览器端 3D 高斯泼溅编辑器 — 在 Web 上编辑现实
前端·javascript·webgl
supermapsupport9 天前
SuperMap iClient3D for WebGL 根据实体高度进行差异化颜色渲染
webgl
HYCS10 天前
用pixijs实现fabricjs(一):FakeCanvasRenderingContext2D
javascript·webgl·canvas
qiao若huan喜11 天前
14、webgl 基本概念 + 图形变换
webgl
李伟_Li慢慢12 天前
ShaderToy-山峦+蓝天+白云
前端·webgl
爱看书的小沐14 天前
【小沐杂货铺】基于Three.js绘制三维艺术画廊3DArtGallery (Three.js,WebGL)
javascript·3d·webgl·three.js·babylon.js·三维画廊