2

I need to use the multiply blending mode when drawing on a HTML canvas:

ctx.globalCompositeOperation = "multiply";
ctx.drawImage(...);

I get the expected result in latest Chrome/Firefox but not in IE 11: it doesn't crash but I get the same result as when not specifying the globalCompositeOperation property.

How can I programatically test whether the browser supports the multiply blending mode?

sdabet
  • 18,360
  • 11
  • 89
  • 158
  • To this day, does mobile browsers still not support the 'multiply' value??? Having issues even today in 2016 to get the same effect rendered from desktop on ios devices (doesn't show up at all on ios safari and chrome) – chamberlainpi May 30 '16 at 11:39

2 Answers2

3

Just as many operations on the context, a wrong input to globalCompositeOperation is just ignored, so it's very easy to see if a given mode is supported : just set it, then read the current mode to check it's the one you provided.
So just to be clear, you could use some function like this one :

// setCompositeMode : sets the globalCompositeOperation on provided context.
// return true if mode is supported, false otherwise.
function setCompositeMode(ctx, newMode) {
    ctx.globalCompositeOperation = newMode;
    return ( ctx.globalCompositeOperation == newMode ) ;
}

Just a small example :

var cv=document.createElement('canvas');
var ctx= cv.getContext('2d');

console.log(" Current (default) composite mode : " + ctx.globalCompositeOperation ) ;
console.log("setting 'destination-in'.");
ctx.globalCompositeOperation = 'destination-in';
console.log(" composite mode : " + ctx.globalCompositeOperation ) ;
console.log("setting 'multiply'.");
ctx.globalCompositeOperation = 'multiply';
console.log(" composite mode : " + ctx.globalCompositeOperation ) ;
console.log("setting 'i-don-t-exist' .");
ctx.globalCompositeOperation = 'i-don-t-exist';
console.log(" composite mode : " + ctx.globalCompositeOperation ) ;

Output (on Chrome/mac OS, supporting multiply) :

" Current (default) composite mode : source-over"
"setting 'destination-in'."
" composite mode : destination-in"
"setting 'multiply'."
" composite mode : multiply"
"setting 'i-don-t-exist' ."
" composite mode : multiply"
GameAlchemist
  • 18,995
  • 7
  • 36
  • 59
2

Since the context API impliments composite modes as internal browser properties, you'll probably have to actually execute .globalCompositeOperation='multiply' and see if the result is valid:

// pre-flight compatibility tests
ctx.fillStyle='black';
ctx.fillRect(0,0,1,1);
ctx.globalCompositeOperation='multiply';
ctx.fillStyle='white';
ctx.fillRect(0,0,1,1);
var supportsMultiplyCompositing=(ctx.getImageData(0,0,1,1).data[0]===0);
markE
  • 102,905
  • 11
  • 164
  • 176
  • 1
    Well, I hoped there would be some clean way to do that..but your solution works anyway. Thanks! – sdabet Sep 30 '14 at 15:52