konvajs/konva

After changing and puttingImageData, the result of layer.toDataURL is not updated

JaxonSong opened this issue · 1 comments

Hey guys, I need to change the imageData and export it to an image. This is a simple demo. It's refreshed in the browser, but I get a red image when I export it instead of the expected updated green image.

const initCanvas = () => {
  mainStage = new Konva.Stage({
    container: "main-canvas",
    width: canvasWidth,
    height: canvasHeight,
    draggable: false,
  });

  mainLayer = new Konva.Layer({
    draggable: false,
    listening: false,
    width: canvasWidth,
    height: canvasHeight,
  });
  mainLayer.getCanvas().pixelRatio = 1;

  const rect = new Konva.Rect({
    x: 0,
    y: 0,
    width: canvasWidth,
    height: canvasHeight,
    fill: "red",
  });
  mainLayer.add(rect);
  mainStage.add(mainLayer);
};

const exportStage = () => {
  const ctx = mainLayer.getContext();
  const imageData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);

  for (let i = 0, len = imageData.data.length; i < len; i += 4) {
    imageData.data[i] = 0;
    imageData.data[i + 1] = 255;
    imageData.data[i + 2] = 0;
    imageData.data[i + 3] = 255;
  }
  ctx.clearRect(0, 0, canvasWidth, canvasHeight);
  ctx.putImageData(imageData, 0, 0);

  const url = mainLayer.toDataURL({
    x: 0,
    y: 0,
    width: canvasWidth,
    height: canvasHeight,
    mimeType: "image/png",
    quality: 1,
  });
  console.log(url);
};

node.toDataURL() creates new (empty) canvas in memory and renders all shapes into it. Direct pixel change is not preserved. If you need to do that, you can export first, then change pixels of exported result.