nodeca / pica

Resize image in browser with high quality and high speed

Home Page:http://nodeca.github.io/pica/demo/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Custom background for transparent image

DZakh opened this issue · comments

I want to set a background for a transparent image. But can't figure out how to do it. I've tried to modify the createCanvas option, but it didn't work this way in some reason.

const pica = new Pica({
  createCanvas: function (width, height) {
    const canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;

    const ctx = canvas.getContext('2d');
    ctx.fillStyle = 'blue';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    return canvas;
  },
});

p.s. I use pica together with the image-blob-reduce so the createCanvas is also used to create an initial canvas.

Sorry, that's out of package scope. It's for resize only.

Well, I've just found why my solution doesn't work. It's in the __extractTileData method because of tmpCtx.globalCompositeOperation = 'copy';. I see your point that it's for resize only, but I don't like the idea to do the processing logic twice just to set another color for background when converting png to jpeg. Ok, I'll try to figure out some rational solution, thanks for your fast response.

this.debug('Draw tile imageBitmap/image to temporary canvas');
  var tmpCanvas = this.options.createCanvas(tile.width, tile.height);
  var tmpCtx = tmpCanvas.getContext('2d', {
    alpha: Boolean(opts.alpha)
  });
  tmpCtx.globalCompositeOperation = 'copy';
  tmpCtx.drawImage(stageEnv.srcImageBitmap || from, tile.x, tile.y, tile.width, tile.height, 0, 0, tile.width, tile.height);
  this.debug('Get tile pixel data');
  extractTo.src = tmpCtx.getImageData(0, 0, tile.width, tile.height).data; // Safari 12 workaround
  // https://github.com/nodeca/pica/issues/199