我有一个 Blazor WebAssembly 应用程序从计算机网络摄像头捕获视频。链接到网络摄像头的视频元素被隐藏。视频提要被绘制到 HTML 画布元素。
我正在使用 JSInterop 在画布上调用 GetImageData()。该函数将部分画布的图像作为图像返回。
当我从 JavaScript 函数返回图像时,我得到:
“dotnet.wasm:1 Uncaught (in promise) RuntimeError: memory access out of bounds error”
这是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;
}