Blazor WebAssembly从JSInterop调用返回图像时出现“内存访问超出范围错误”

时间:2020-06-14 04:44:26

标签: javascript blazor-client-side blazor-webassembly blazor-jsinterop

我有一个Blazor WebAssembly应用程序,可从计算机网络摄像头捕获视频。链接到网络摄像头的视频元素被隐藏。视频供稿绘制为HTML canvas元素。

我正在使用JSInterop在画布上调用GetImageData()。该函数返回画布的一部分图像作为图像。

当我从JavaScript函数返回图像时,我得到一个:

“ dotnet.wasm:1未捕获(承诺)RuntimeError:内存访问超出范围错误”

这是HTML:

<div id="container">
    <video id="videoElement" @ref="VideoElement" autoplay="true" width="1280" height="720"></video>
    <canvas id="videoCanvas" @ref="VideoCanvas" width="1280" height="720"></canvas>
</div>

这是引起问题的代码。我将其范围缩小到OnTimedEvent中的行:

@code {
    ElementReference VideoElement;
    ElementReference VideoCanvas;

    protected async override Task OnAfterRenderAsync(bool firstRender)
    {
        await JSRuntime.InvokeVoidAsync("StartVideo", VideoElement);
        await JSRuntime.InvokeVoidAsync("PaintVideoToCanvas", VideoElement, VideoCanvas);

        Timer _timer = new Timer(5000);
        _timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        _timer.Start();
    }

    private async void OnTimedEvent(object source, ElapsedEventArgs e)
    {    
        Image temp = await JSRuntime.InvokeAsync<Image>("ImageScanner", VideoCanvas);
    }
}

这是JavaScript:

function StartVideo(VideoElement) {

    let video = VideoElement;

    if (navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia({ video: { width: { min: 1280 }, height: { min: 720 } } })
            .then(function (stream) {
                video.srcObject = stream;
            })
            .catch(function (err0r) {
                console.log("Something went wrong!");
            });
    }
}

function PaintVideoToCanvas(VideoElement, VideoCanvas) {

    let video = VideoElement;
    let canvas = VideoCanvas;

    let ctxLayer1 = canvas.getContext("2d");
    StartVideo();

    function StartVideo() {
        ctxLayer1.drawImage(video, 0, 0);
        setTimeout(StartVideo, 1000 / 30); // drawing at 30fps
    }
}

function ImageScanner(VideoCanvas) {

    let video = VideoCanvas;

    let ctxQRCapture = video.getContext("2d");

    let image = ctxQRCapture.getImageData(950, 260, 200, 200);

    return image;
}

0 个答案:

没有答案