在JavaScript中按值复制imageData [英] Copy imageData by value in JavaScript
问题描述
在我的应用程序中,我有一个函数来处理Canvas ImageData。它看起来像这样:
In my application I have a function that processes Canvas ImageData. It looks something like this:
function processData(imagedata, filters) {
var data = imagedata.data;
//manipulate data with filters
imageData.data = data;
return imageData;
}
我一直在使用它:
var imageData = processData(imageData, {...});
b
$ b
But because the imageData object is passed by reference it will also work like this:
processData(imageData, {...}); // no assignment
我来到一个点,在我的项目中,我需要能够处理一些imageData,同时仍然可以访问原始数据。我的第一个尝试类似于以下内容:
I've come to a point in my project where I need to be able to process some imageData while still having access to the original data. My first attempt was similar to the following:
var originalData = imageData;
var processedData = processData(imageData, {...});
这当然会导致相同的imageDatas。
This of course would result in to identical imageDatas.
所以我的第二个想法是编辑processsData函数,所以它以某种方式操作imageData的副本,而不是传递的imageData。我所有的尝试都失败了,或者效率很低。只是想知道是否有一个特殊的方式来做到这一点。提前感谢。
So my second thought was to edit the processsData function so it somehow manipulates a copy of the imageData, instead of the passed imageData. All my attempts to do this have failed or have been horribly inefficient. Just wondering if there is a special way to do this. Thanks in advance.
推荐答案
根据最新规范 ImageData
对象数据
属性初始化为< a href =http://www.khronos.org/registry/typedarray/specs/latest/#7.1> Uint8ClampedArray
对象(而不是之前使用的 CanvasPixelArray
对象),因此 ImageData
中的数据可以使用 set
方法轻松复制:
According to the latest specification ImageData
object data
attribute is initialized to a Uint8ClampedArray
object (instead of earlier used CanvasPixelArray
object), so data within ImageData
could be easily copied with set
method:
function copyImageData(ctx, src)
{
var dst = ctx.createImageData(src.width, src.height);
dst.data.set(src.data);
return dst;
}
这篇关于在JavaScript中按值复制imageData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!