简体   繁体   English

如何在JavaScript中实现多线程?

[英]How do i implement multi-threading in my JavaScript?

My website allow users to record canvas and also draw on the canvas at the same time. 我的网站允许用户记录画布并同时在画布上绘画。 if users start recording the canvas and also start to draw on the canvas the drawing on the canvas it will start to lagg. 如果用户开始记录画布并且还开始在画布上绘制,则画布上的绘图将开始滞后。 I am told that multi-threading web workers should be able to solve the problem. 有人告诉我多线程网络工作者应该能够解决这个问题。 however I am not sure how should I start. 但是我不确定应该如何开始。

Could someone guide me please? 有人可以指导我吗? what should I put in postmessage/onmessage? 我应该在邮件中添加什么?

var recordUrl;
var audioUrl;
var audioStream;
var audiorecorder;
var elementToShare = document.getElementById("elementToShare");
var recorder = RecordRTC(elementToShare, {
    type: 'canvas'
});

document.getElementById('start').onclick = function() {

    /*
    <script id="worker" type="javascript/worker">

    <!--M KY -->
        multithreading
        var blob = new Blob([document.getElementById('worker').textContent]);
        var worker = new Worker(window.webkitURL.revokeObjectURL(blob));
        URL.revokeObjectURL(blob);
        return worker;

        worker.onmessage = function(event) {

        }

        worker.postnmessage = function(event) {

        }
        */
    $('#record').trigger('click');

    if (!audioStream)
        navigator.getUserMedia(audioConstraints, function(stream) {
            if (window.IsChrome) stream = new window.MediaStream(stream.getAudioTracks());
            audioStream = stream;

            // "audio" is a default type
            audiorecorder = window.RecordRTC(stream, {
                type: 'audio',
                bufferSize: typeof params.bufferSize == 'undefined' ? 16384 : params.bufferSize,
                sampleRate: typeof params.sampleRate == 'undefined' ? 44100 : params.sampleRate,
                leftChannel: params.leftChannel || false,
                disableLogs: params.disableLogs || false
            });
            audiorecorder.startRecording();
        }, function() {});
    else {
        audio.src = URL.createObjectURL(audioStream);
        audio.muted = true;
        audio.play();
        if (audiorecorder) audiorecorder.startRecording();
    }

    window.isAudio = true;

    recorder.startRecording();
    document.getElementById('start').disabled = true;
    setTimeout(function() {
        document.getElementById('stop').disabled = false;
    }, 1000);
//worker.terminate();
// }
};

canvas code 画布代码

<div id="cover">
                                <!-- <canvas id="fakecanvas" width="890" height="1267" style="z-index: 2; position: absolute;left:18%"></canvas> -->
                                <canvas id="canvas" width="890" height="1267" style="z-index: 1; border:1px solid black; position: absolute;"></canvas>
                            </div>                          
                        </div>
                    </section>                  
                    <section id="section-2">
                        <div style="width: 100%; height:5%; float:left;">
                        <a id="capture2" onclick="capFunction2();">
                            <input type="image" name="screenshot2" value="Save This Page" style="float: right; width:25px; height:25px;" src="img/camera.png">
                        </a>
                        <script>
                        function downloadCanvas2(link, canvasId, filename) {
                            html2canvas([document.getElementById(canvasId)], {
                                onrendered: function(cvs2) {
                                    //var canvasData = cvs2.toDataURL('image/png');
                                    var link = document.createElement("a");
                                    link.href = cvs2.toDataURL();
                                    link.download = filename;
                                    link.click();
                                }
                            });
                        }

                        document.getElementById('capture2').addEventListener('click', function() {
                            var currentTime2 = new Date().YYYYMMDDHHMMSS();
                            downloadCanvas2(this, 'viewer2', currentTime2 + '.jpg');    
                            }, false);
                        </script>

javaScript is single threaded. javaScript是单线程的。 There is only one javascript thread per window which is frequently termed as Browser UI Thread ("thread" is not necessarily accurate for all browsers). 每个窗口只有一个JavaScript线程,通常被称为浏览器UI线程(“线程”不一定对所有浏览器都准确)。

Question : 题 :

How does asynchronous events like ajax,setTimeout occurs? 像ajax,setTimeout这样的异步事件如何发生?

A browser comes with an inner loop called Event Loop, which checks the queue and process & execute it.So they run only when there is a opening in execution. 浏览器带有一个称为事件循环的内部循环,该循环检查队列并处理并执行它,因此它们仅在执行中存在空缺时才运行。 I can write a long article on how this work but that is out of the context. 我可以写一篇很长的文章,说明这是如何工作的,但是这超出了上下文。

So what is the solution? 那么解决方案是什么? Web workers? 网络工作者?

Yes,it can accomplish some of the feature which a multithreading does. 是的,它可以完成多线程所具有的某些功能。 But it comes with limitations 但是它有局限性

  • It cannot acces DOM. 它不能访问DOM。

  • They cannot access global variable or js functions in main page. 他们无法访问主页中的全局变量或js函数。

  • Access to some objects like window,document & parents is restricted 限制访问某些对象,例如窗口,文档和父对象

So even if you want to acheive multithreading with web workers you may need to modify your code and make it event driven programming rather than data driven coding. 因此,即使您想与Web Workers实现多线程,您可能也需要修改代码并使之成为事件驱动的编程,而不是数据驱动的编码。

Hope it will be useful for you 希望对您有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM