You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity2D WebGL环境下如何通过API返回URL在ImageView中展示网页?

解决方案:Unity2D WebGL 中在 ImageView 显示网页内容

针对 WebGL 平台的限制,以下是三种可行的解决方案,适配不同需求场景:


方案一:JS 网页截图 + Unity 纹理渲染(静态内容展示)

通过 JavaScript 加载目标网页并截图,将图片数据传递给 Unity,再转成纹理赋值给 ImageView,适合仅需展示静态网页内容的场景。

步骤 1:Unity C# 交互脚本

创建脚本挂载到包含 ImageView 的 GameObject 上:

using UnityEngine;
using UnityEngine.UI;

public class WebStaticLoader : MonoBehaviour
{
    public Image targetImageView;

    // 触发网页加载与截图(三个画面展示完成后调用此方法)
    public void LoadWebContent(string targetUrl)
    {
#if UNITY_WEBGL && !UNITY_EDITOR
        Application.ExternalCall("CaptureWebPage", targetUrl, gameObject.name, "OnCaptureComplete");
#endif
    }

    // JS 回调接收截图数据
    public void OnCaptureComplete(string base64Image)
    {
        // 解析 Base64 为纹理
        byte[] imageBytes = System.Convert.FromBase64String(base64Image);
        Texture2D webTexture = new Texture2D(2, 2);
        webTexture.LoadImage(imageBytes);
        
        // 生成 Sprite 并赋值给 ImageView
        Sprite webSprite = Sprite.Create(webTexture, new Rect(0, 0, webTexture.width, webTexture.height), new Vector2(0.5f, 0.5f));
        targetImageView.sprite = webSprite;
    }
}

步骤 2:WebGL JS 插件

在 Unity 项目的 Plugins/WebGL 目录下创建 WebCapture.jslib 文件:

mergeInto(LibraryManager.library, {
    CaptureWebPage: function(urlPtr, gameObjNamePtr, callbackNamePtr) {
        const url = Pointer_stringify(urlPtr);
        const gameObjName = Pointer_stringify(gameObjNamePtr);
        const callbackName = Pointer_stringify(callbackNamePtr);

        // 创建隐藏 iframe 加载网页
        const iframe = document.createElement('iframe');
        iframe.style.display = 'none';
        iframe.src = url;
        document.body.appendChild(iframe);

        iframe.onload = () => {
            // 使用 html2canvas 截图(需在 index.html 引入该库)
            html2canvas(iframe.contentDocument.body).then(canvas => {
                // 移除 Base64 前缀并传递给 Unity
                const base64Data = canvas.toDataURL('image/png').replace(/^data:image\/png;base64,/, "");
                sendMessage(gameObjName, callbackName, base64Data);
                document.body.removeChild(iframe);
            });
        };
    }
});

步骤 3:配置 index.html

在 WebGL 构建后的 index.html 头部引入 html2canvas 库:

<script src="html2canvas.min.js"></script>

(将 html2canvas.min.js 放入 Unity 的 StreamingAssets 目录,构建时会自动复制到输出文件夹)


方案二:专用 WebGL 网页渲染插件(支持交互)

使用支持 WebGL 平台的 Unity 网页渲染插件(如 Unity Web Browser),这类插件能直接在 UI 组件中嵌入可交互的网页,无需手动处理 JS 交互与渲染逻辑,只需配置组件的 URL 属性即可实现需求。


方案三:优化 IFrame 层级与坐标映射(可交互网页)

如果之前使用 IFrame 效果不佳,可通过精确控制 IFrame 的位置、大小与层级,使其与 ImageView 视觉对齐,适合需要网页交互能力的场景。

步骤 1:Unity C# 控制脚本

using UnityEngine;
using UnityEngine.UI;

public class WebIframeController : MonoBehaviour
{
    public Image targetImageView;

    public void ShowInteractiveWebPage(string targetUrl)
    {
#if UNITY_WEBGL && !UNITY_EDITOR
        RectTransform rect = targetImageView.GetComponent<RectTransform>();
        // 将 UI 坐标转换为屏幕像素坐标
        Vector2 screenPos = RectTransformUtility.WorldToScreenPoint(Camera.main, rect.position);
        Vector2 uiSize = rect.rect.size;
        
        // 适配 Canvas 缩放比例
        CanvasScaler scaler = FindObjectOfType<CanvasScaler>();
        float scale = scaler.scaleFactor;
        screenPos /= scale;
        uiSize /= scale;

        // 调用 JS 调整 IFrame
        Application.ExternalCall("AdjustIframe", targetUrl, screenPos.x - uiSize.x/2, screenPos.y - uiSize.y/2, uiSize.x, uiSize.y);
#endif
    }
}

步骤 2:index.html 中的 JS 逻辑

在 index.html 的 <body> 内添加以下代码:

function AdjustIframe(url, x, y, width, height) {
    let iframe = document.getElementById('unity-web-iframe');
    if (!iframe) {
        iframe = document.createElement('iframe');
        iframe.id = 'unity-web-iframe';
        iframe.style.position = 'absolute';
        iframe.style.border = 'none';
        document.body.appendChild(iframe);
    }
    iframe.src = url;
    iframe.style.left = `${x}px`;
    iframe.style.top = `${y}px`;
    iframe.style.width = `${width}px`;
    iframe.style.height = `${height}px`;
    iframe.style.display = 'block';
    // 调整层级让 IFrame 显示在 Unity 画布上方
    iframe.style.zIndex = 1;
    document.getElementById('unity-container').style.zIndex = 0;
}

内容的提问来源于stack exchange,提问作者Ruchita P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 10:10:16