How can I flip the result of WebGLRenderingContext.readPixels()?

前端 未结 3 710
无人及你
无人及你 2021-01-14 02:55

Why is the imageData that I get from WebGLRenderingContext.readPixels() upside down?

I try to do the folowing:

var gl = renderer.domElem         


        
3条回答
  •  庸人自扰
    2021-01-14 03:54

    I don't know a webgl way to flip readPixels, and I suspect there is indeed a way to "avoid the problem altogether", but since you seem to draw it on a 2DContext anyway, here is a way to flip your putImageData.

    Since putImageData is not affected by context's transforms, simply doing ctx.scale(1,-1); ctx.putImageData() won't work.

    You'll need to putImageData, then flip its transforms, before drawing the canvas on itself.

    Use globalCompositeOperation = 'copy' if you have transparency.

    function flip(imageData){
      var ctx = flipped.getContext('2d');
      flipped.width = imageData.width;
      flipped.height = imageData.height;
      // first put the imageData
      ctx.putImageData(imageData, 0,0);
      // because we've got transparency
      ctx.globalCompositeOperation = 'copy';
      ctx.scale(1,-1); // Y flip
      ctx.translate(0, -imageData.height); // so we can draw at 0,0
      ctx.drawImage(flipped, 0,0);
      // now we can restore the context to defaults if needed
      ctx.setTransform(1,0,0,1,0,0);
      ctx.globalCompositeOperation = 'source-over';
      }
    
    /* remaining is just for the demo */
    var ctx = normal.getContext('2d');
    var img = new Image();
    img.crossOrigin = 'anonymous';
    img.onload = getImageData;
    img.src = "https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png";
    
    function getImageData(){
      normal.width = this.width;
      normal.height = this.height;
      ctx.drawImage(this, 0,0);
      imageData = ctx.getImageData(0,0,this.width, this.height);
      flip(imageData);
      }
    canvas{border: 1px solid}
    body{background: ivory;}
    
    

提交回复
热议问题