Efficient javascript equivalent of Processing functions

孤街浪徒 提交于 2020-01-03 01:17:28

问题


I tweaked a Processing sketch to produce a variant of a TV static effect I need for a web app. Now I want to convert this effect into JS/canvas. What are the pure javascript/canvas equivalents of loadPixels(), copyArray(), updatedPixels(), and draw() as given in the following Processing code, or how best to go about the conversion given that, probably, JS/canvas are not as efficient as Processing/Java?

int[] ppx;
Random generator = new Random();

void setup() {
  size(640,480);
  loadPixels();  
  ppx = new int[pixels.length];
  for (int y = 0; y < ppx.length;y++) {
      int spread = generator.nextInt(5);
      switch(spread) {
        case(1):
            if(y-480 > 0) {
                ppx[y] = ppx[y-480];
            }
            break;
        case(2):
            if(y-1 > 0) {
                ppx[y] = ppx[y-1];
            }
            break;
        case(3):
            ppx[y] = color(0,generator.nextInt(2)*255,0);
            if(y+480 < ppx.length) {
                ppx[y+480] = ppx[y];
            }
            break;
        case(4):
            ppx[y] = color(0,generator.nextInt(2)*255,0);
            if(y+1 < ppx.length) {
                ppx[y+1] = ppx[y];
            }
            break;
        case(0):
            break;
      };
  }
  frameRate(100000000000L);

}
void draw() {
  for (int y = 0; y < height;)
     arrayCopy(ppx, generator.nextInt(height/2), pixels, y++*width,width);
  updatePixels();
}

回答1:


You can use John Resig's Processing.js for a one shot conversion: http://processingjs.org/

Canvas and JS works is a bit more low level maybe start here : http://net.tutsplus.com/tutorials/javascript-ajax/canvas-from-scratch-pixel-manipulation/




回答2:


I've implemented these functions so far with s pointing to a HTMLCanvasElement. Jury is still out on whether arrayCopy can be improved without loop unrolling:

    var x = s.getContext('2d');
    var pixels;
    function arrayCopy(src,sstart,dst,dstart,length) {
            length += sstart;
            dstart += length;
            while(--length > sstart) {
                    dst[--dstart] = src[length];    
            }       
    }
    function loadPixels() {
            pixels = x.getImageData(0,0,s.width,s.height);
    }
    function updatePixels() {
            x.putImageData(0,0,pixels);
    }

I'm still unsure about how to make the JS equivalent of a draw() function.



来源:https://stackoverflow.com/questions/15501251/efficient-javascript-equivalent-of-processing-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!