Последовательная оптимизация холста - PullRequest
0 голосов
/ 07 марта 2019

Привет, я создаю приложение, в котором мне нужно манипулировать png: извлечь цвет, создать контур и т. Д. ...

Каждый раз, когда я повторяю один и тот же процесс:

  1. Дождитесь загрузки изображения в DOM
  2. Создайте новый холст размером
  3. Добавьте context2D
  4. DrawImage
  5. GetImageData
  6. Сделайте некоторые вещи сцикл через все пиксели данных
  7. Поместить новый материал (putImageData) в пустой массив данных пикселей (создать с помощью createImageData)
  8. Ссылка на новый холст
  9. Создать зановоизображение с этого холста
  10. повтор

Например:

var imgColor = new Image();
imgColor.src = this[`canvasColor${color}`].toDataURL("image/png");

// wait for load of this new color image
imgColor.onload = () => {
  this[`canvasColorAndOutline${color}`].width = width;
  this[`canvasColorAndOutline${color}`].height = height;
  var outlineAndColorCtx = this[`canvasColorAndOutline${color}`].getContext("2d");
  var dArr = [-1, -1, 0, -1, 1, -1, -1, 0, 1, 0, -1, 1, 0, 1, 1, 1], // offset array
    s = this.state.outlineThickness,  // thickness
    i = 0,  // iterator
    x = 0,  // final position
    y = 0;

  // draw images at offsets from the array scaled by s
  for (; i < dArr.length; i += 2) {

    outlineAndColorCtx.drawImage(imgColor, x + dArr[i] * s, y + dArr[i + 1] * s);
  }

  // fill with color
  outlineAndColorCtx.globalCompositeOperation = "source-in";
  outlineAndColorCtx.fillStyle = "YELLOW";
  outlineAndColorCtx.fillRect(0, 0, width, height);

  // draw original image in normal mode
  outlineAndColorCtx.globalCompositeOperation = "source-over";
  outlineAndColorCtx.drawImage(imgColor, x, y);

  ///////////////
  // THIRD STEP : remove the white to keep the outline
  //////////////

  // create a new image with this color context to work on
  var imgOutline = new Image();
  imgOutline.src = this[`canvasColorAndOutline${color}`].toDataURL("image/png");
  imgOutline.onload = () => {
    var imageDataOutlineAndColor = outlineAndColorCtx.getImageData(0, 0, width, height)
    this[`canvasOutline${color}`].width = width;
    this[`canvasOutline${color}`].height = height;
    const outlineCtx = this[`canvasOutline${color}`].getContext("2d");
    const imageDataOutline = outlineCtx.createImageData(width, height);

    for (let i = 0; i < imageDataOutlineAndColor.data.length; i += 4) {

      if (
        (imageDataOutlineAndColor.data[i + 0] > 100) &&
        (imageDataOutlineAndColor.data[i + 1] > 100) &&
        (imageDataOutlineAndColor.data[i + 2] < 5) &&
        (imageDataOutlineAndColor.data[i + 3] != 0)
      ) {
        imageDataOutline.data[i + 0] = 255;
        imageDataOutline.data[i + 1] = 255;
        imageDataOutline.data[i + 2] = 0;
        imageDataOutline.data[i + 3] = 255;
      }
    }
    outlineCtx.putImageData(imageDataOutline, 0, 0);
  }
}

У меня вопрос : есть ли способ ярлыка, шаг 78,9, чтобы избежать времени img.load?и напрямую использовать контекст?Поэтому я буду постоянно использовать один и тот же контекст, он просто изменяется на каждом шаге процесса.И более глобально, есть ли способ оптимизировать это?

...