Ask Your Question
0

opencv.js doesn't loaded even after 'onload' event occurs

asked 2020-10-15 03:48:58 -0600

updated 2020-10-15 03:52:54 -0600

I get error like "cv.Mat is not a constructor" or "cv is not defined". My code is:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script async src="js/opencv.js"  onload="onOpenCvReady()" type="text/javascript"></script>
</head>
<body>
    <canvas id="canvasOutput" width="300" height="300"></canvas>  
    <script type="text/javascript">
        var scene = new Image();
        scene.src = 'templates/Scene_7.png';

        window.addEventListener("load", function () {
            try {
                let scene1 = cv.imread(scene);
                cv.imshow('canvasOutput', scene1);
            }
            catch (e) {
            }
        }, false);

        function onOpenCvReady() {
            try {
                let scene1 = cv.imread(scene);
                cv.imshow('canvasOutput', scene1);
            }
            catch (e) {
            }
        }
    </script>
</body>
</html>

But, if I change code to

<input id="Button" onclick="start();" type="button" value="Start" />
 function start() {
            try {
                let scene1 = cv.imread(scene);
                cv.imshow('canvasOutput', scene1);
            }
            catch (e) {
            }
        }

and press the button "Start", then everything is OK. So, I think opencv.js doesn't load even after onOpenCvReady() and window "load" events occur. But why?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
0

answered 2020-10-15 11:23:20 -0600

kpachinger gravatar image

The concept of "loaded" can be a "race" condition. The window may (or may not) "load" before the OpenCV file. There are many efforts to detect "load" consistently across browsers. Sometimes to avoid overly-complex relational logic chains you use "buttons".

Ideally it is cached, i.e. didn't "load" at all. It's good to understand "load"... but use the "load" chaining techniques from library examples... i.e. a "callback" for a cascade. Especially with recurring "calls". This is best for large files and long-running functions. I "promise"!

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2020-10-15 03:48:58 -0600

Seen: 1,544 times

Last updated: Oct 15 '20