Copy imageData by value in JavaScript

前端 未结 3 1293
暖寄归人
暖寄归人 2020-12-31 08:52

In my application I have a function that processes Canvas ImageData. It looks something like this:

function processData(imagedata, filters) {
  var data = im         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-31 09:27

    I think you should be able to create a copy pretty easily:

    function copyImageData(context, original) {
      var rv = context.createImageData(original.width, original.height);
      // would 
      //   rv.data = Array.prototype.slice.call(original.data, 0);
      // work?
      for (var i = 0; i < original.data.length; ++i)
        rv.data[i] = original.data[i];
      return rv;
    }
    

    (The first argument is the graphics context.)

    Then you can call "processImageData" with a copy:

    var newImage = processImageData(copyImageData(context, imageData));
    

    edit — I'll try a fiddle to see whether ".slice()" works on the "data" array - I think it will but it's always good to make sure.

提交回复
热议问题