blueimp/JavaScript-Load-Image

Add canvas fillStyle to options

florianPopulaer opened this issue · 2 comments

Transparent backgrounds on png images are drawn on the canvas with a black background when img.toBlob() is set to image/jpeg.
My suggestion: Adding an option to set the fillStyle of the canvas. I tried hacking it in. Worked so far.

x.renderImageToCanvas=function(e, t, i, n, a, o, r, s, l, c, d) {
var u=e.getContext("2d");
u.fillStyle = '#FFFFFF';
u.fillRect(0,0,l,c);
...

Hi @florianPopulaer, thanks for your suggestion.

I don't think we need this in the library, since you can add background colors to a transparent image drawn on a canvas afterwards by setting CanvasRenderingContext2D.globalCompositeOperation to 'destination-over' before executing fillRect().

Here's a sample function to add a background color to a given canvas:

function addBackgroundColor(canvas, color) {
  var ctx = canvas.getContext('2d')
  var originalCompositeOperation = ctx.globalCompositeOperation
  ctx.globalCompositeOperation = 'destination-over'
  ctx.fillStyle = color
  ctx.fillRect = ctx.fillRect(0, 0, canvas.width, canvas.height)
  ctx.globalCompositeOperation = originalCompositeOperation
}
vvo commented

I stumbled on this tip while searching for how to replace the background color of an existing canvas. Thanks so much :)