blueimp / JavaScript-Load-Image

Load images provided as File or Blob objects or via URL. Retrieve an optionally scaled, cropped or rotated HTML img or canvas element. Use methods to parse image metadata to extract IPTC and Exif tags as well as embedded thumbnail images, to overwrite the Exif Orientation value and to restore the complete image header after resizing.
https://blueimp.github.io/JavaScript-Load-Image/
MIT License
4.46k stars 923 forks source link

Add canvas fillStyle to options #102

Closed florianPopulaer closed 4 years ago

florianPopulaer commented 4 years ago

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); ...

blueimp commented 4 years ago

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 3 years ago

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