11

这是有效的,但我觉得这段代码很长。我正在寻找更好的主意。

var clone = function(imageData) {
  var canvas, context;
  canvas = document.createElement('canvas');
  canvas.width = imageData.width;
  canvas.height = imageData.height;
  context = canvas.getContext('2d');
  context.putImageData(imageData, 0, 0);
  return context.getImageData(0, 0, imageData.width, imageData.height);
};
4

3 回答 3

15

ImageData构造函数接受图像数据数组。

const imageDataCopy = new ImageData(
  new Uint8ClampedArray(imageData.data),
  imageData.width,
  imageData.height
)
于 2018-01-03T13:31:06.673 回答
11

TypedArray.prototype.set()可以直接复制数据。

var imageDataCopy = new Uint8ClampedArray(originalImageData.data);
imageDataCopy.data.set(originalImageData.data);

这会将 的内容设置imageDataCopy为与 相同originalImageData

于 2012-12-13T15:20:50.023 回答
-2

大多数情况下,只需将 分配给一个新变量就足够了imageData,就像:

myImgData=ctx.getImageData(0,0,c.width,c.height); //get image data somewhere
imgDataCopy = myImgData;   // clone myImgData

...现在imgDataCopy包含myImgData. ‍♂️</p>


演示

下面的代码片段在 's 数组中创建了 4 个“帧”,ImageData然后循环遍历它们。

const c = document.getElementById('canvas'),
      ctx = c.getContext("2d");
var wh=70, iDatas=[], i=0,
    lines=[[10,10,wh-10,wh-10], [wh/2,5,wh/2,wh-5],  // ⤡,↕
           [wh-10,10,10,wh-10], [5,wh/2,wh-5,wh/2]]; // ⤢,↔
c.width=wh;
c.height=wh;

ctx.strokeStyle='blue'; //setup to draw
ctx.lineWidth=9;
ctx.lineWidth='round';

for(var [x1,y1,x2,y2] of lines){ 
  ctx.beginPath();
  ctx.moveTo(x1,y1); //draw something
  ctx.lineTo(x2,y2);
  ctx.stroke();
  var d=ctx.getImageData(0,0,c.width,c.height); //get imgdata
  iDatas.push( d ); //save imgdata to array
  ctx.clearRect(0, 0, c.width, c.height); //clear canvas
}

ctx.strokeStyle='green'; //❌has no effect: 
  //  ↑ shows that color data comes from the source (can't be changed)
ctx.lineWidth='round'; //❌has no effect: 
  //  ↑ shows that non-color styling does NOT come from source (CAN'T be changed)

//now you can refer to the image data as iData[i] where i= 0 to 3
drawFrame();
function drawFrame(){
  ctx.putImageData( iDatas[i],0,0); //draw imgData from array
  i=(i==3?0:i+1); //set next iteration #
  setTimeout(function(){ drawFrame() }, 100); //schedule next frame
}
canvas{ border:2px dotted salmon; }
<canvas id='canvas'></canvas>

于 2021-09-11T00:51:51.833 回答