htmlcanvashtml5-canvasglobalcompositeoperation

Test if browser supports "multiply" for globalCompositeOperation canvas property


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?


Solution

  • 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"