Canvas工作线程Worker20

Canvas工作线程

/*当某个操作比较耗时时,可以把这些放在另一个线程中进行处理,处理时需要注意它的postMessage onmessage方法是定死的*/
var sunglassFilter = new Worker('sunglassFilter.js');
sunglassFilter.postMessage( context.getImageData(0, 0, canvas.width, canvas.height) );//向工作线程传递参数,参数封装在event.data中
//sunglassFilter.postMessage({dd:context.getImageData(0, 0, canvas.width, canvas.height), bb:"ddd"});多参数传递
sunglassFilter.onmessage = function (event) {context.putImageData(event.data, 0, 0);//工作线程执行后的回调函数

//sunglassFilter.js
onmessage = function (event) {//event is MessageEvent instance 
   var imagedata = event.data,//var imagedata = e.data["dd"];多参数接收
       data = imagedata.data,
       length = data.length,
       width = imagedata.width;//在这个方法中的console并不会打印到控制台

   for (i=0; i < length; ++i) {
      if ((i+1) % 4 != 0) {   
         if ((i+4) % (width*4) == 0) { // last pixel in a row
            data[i] = data[i-4];
            data[i+1] = data[i-3];
            data[i+2] = data[i-2];
            data[i+3] = data[i-1];
            i+=4;
         }
         else {
           data[i] = 2*data[i] - data[i+4] - 0.5*data[i+4];
         }
      }
   }

   postMessage(imagedata);
};

你可能感兴趣的:(#,Canvas,js,canvas)