网络工作者不起作用

时间:2011-04-26 00:28:23

标签: javascript html5

有人可以告诉我为什么我的网络工作者不起作用? 我画了一个运行良好的动画画布。但是当我通过文本框调整它时,它会停止运行,直到执行JavaScript。现在,我创建了一个工作者来承担调整图形大小的任务,而不停止画布的移动。我希望它更新隐藏字段的值,通过取值文本框,转换为字符串,然后将结果设置为隐藏字段值。为此,我制作文件。我的意思是html标记中没有JavaScript代码。代码文件如下:

/* Code that will be run by the worker */

function applyChanges(radius, size) {
    return radius + "," + size;
}

/*
    Add an event listener to the worker, this will be called when      
    the worker receives a message from the main page.
*/
this.onmessage = function (event) {
    var data = event.data;

    // Message sent by the worker to the main page.
    postMessage(applyChanges(data.radius, data.size));
}

/* Worker's code */

// Create a new worker
var myWorker = new Worker("C:\applications\bb\scripts\setValues.js");
/*
    Add a event listener to the worker, this will be called whenever the worker posts any message.
*/
myWorker.onmessage = function (event) {
    document.getElementById().value = event.data;
};

// Register events for button.
document.getElementById("button").onclick = function () {
    var circle = document.getElementById("tcircle");
    var square = document.getElementById("tsquare");
    var radius = circle.value;
    var size = square.value;

    // check if those are numerics
    if (!isNaN(radius) && !isNaN(size)) {
        // verify that the won't hide more the 1/4 of the circle.
        if (radius >= size / Math.SQRT2) {
            // since we are going to test scrolling and zooming, we are not going to  set max values of radius and size.

            message = { "tcircle": radius, "tsize": size };

            // Message sent by the main page to the worker.
            myWorker.postMessage(message);

        }
        else {
            alert("The radius must not be less that: size/sqrt(2)");
        }
    }
    else {
        alert("Required numeric type!");
    }
}

// Terminate the worker.
myWorker.terminate(); 

2 个答案:

答案 0 :(得分:3)

Web Workers是异步JavaScript处理环境,无法访问其主机环境:DOM。在Web工作者中,您可以卸载强大的算法,数学计算,但是您无法访问表单元素,更改或访问DOM,我也相信您不能生成ajax请求。

答案 1 :(得分:0)

目前Chrome已允许更新,可能有助于解决此问题。

根据这个答案,使用Chrome可以将数据传回给工作人员,然后将其写回画布,以便其他人可以关注,但至少这是继续测试的一种方式。

Web Workers and Canvas

您可能希望了解此演示如何运作,以了解您可以使用WebWorkerCanvas执行的操作。

http://www.robodesign.ro/coding/html5-demo-video-histogram/index-web-worker.html