javascriptxorhtml5-canvasglobalcompositeoperation

Using HTML5's globalCompositeOperation "xor" with shape and text elements in Chrome


I have run into an issue when attempting to globalCompositeOperation to mask/blend shapes and text (shapes mask/blended with other shapes works just fine) in Chrome (more specifically I am using Chrome 12.0.7). Can anyone suggest where I might have gone astray here or suggest a workaround within the canvas element?

Here is an image showing what I'm seeing: https://i.sstatic.net/wRunv.jpg


Here is the code that will reproduce these results:

<!DOCTYPE HTML>
<html>
<body>

<canvas id="testCanvas" width="500" height="500"></canvas>

<script type="text/javascript">
    // setup canvas
    var tcanvas = document.getElementById("testCanvas");
    var tcontext = tcanvas.getContext("2d");

    // draw square
    tcontext.fillStyle = "#FF3366";
    tcontext.fillRect(15,15,70,70);

    // set composite property
    tcontext.globalCompositeOperation = "xor";

    // draw text
    tcontext.fillStyle="#0099FF";
    tcontext.font = "35px sans-serif";
    tcontext.fillText("test", 22, 25);
</script>

</body>
</html>

Solution

  • seems like the XOR globalCompositeOperation problem is a chrome bug that happens only with fillText.

    Other drawing methods seem to work, see here: http://jsfiddle.net/Y5wvb/

    You should report this bug to the Chromium project: http://code.google.com/p/chromium/issues/list
    When you do, post the url of the posted issue here to we can vote it up :)

    I found out that if you change the order of drawing, e.g. draw the text before filling the rectangle, the XOR works just fine. see here: http://jsfiddle.net/Y5wvb/1/