title: Drawing the Difference of two Images to Canvas
body: <p>I am trying to draw the difference of two <a href="https://api.flutter.dev/flutter/dart-ui/Image-class.html" rel="nofollow noreferrer"><code>Image</code></a>s I have to the <a href="https://api.flutter.dev/flutter/dart-ui/Canvas-class.html" rel="nofollow noreferrer"><code>Canvas</code></a> in Flutter and what I really mean is that I only want to <em>draw what is different</em> (you can see what I expect to see below).<br>
  It needs to happen <strong>synchronously</strong>, i.e. in a <a href="https://api.flutter.dev/flutter/rendering/RenderObject/paint.html" rel="nofollow noreferrer"><code>paint</code></a> call!</p>
  
  <p>In this answer, the two images are referred to as <code>imageA</code> and <code>imageB</code>.</p>
  
  <h2>Code</h2>
  
  <pre class="lang-dart prettyprint-override"><code>canvas.drawImage(
    imageA,
    offset,
    Paint(),
  );
  canvas.drawImage(
    imageB,
    offset,
    Paint()
      ..blendMode = BlendMode.difference,
  );
  </code></pre>
  
  <h2>Visualization</h2>
  
  <p><a href="https://i.stack.imgur.com/COs2g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/COs2g.png" alt=""></a></p>
  
  <p><sup><code>imageA</code> and <code>imageB</code> drawn separately.</sup></p>
  
  <p><a href="https://i.stack.imgur.com/ZP681.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZP681.png" alt=""></a></p>
  
  <p><sup>Difference between <code>imageA</code> and <code>imageB</code>. You can see what I <strong>expect</strong> to see <em>left</em> and what I actually get using the code above <em>right</em>.<br>
  The gray/white background color in the left image is supposed to be <em>transparent</em>, i.e. alpha should equal zero where the two images are the same. Additionally, the black shadow around the red square in the <code>expected</code> image is an artifact and not what I want in my app.</sup></p>
  
  <h2>Problem</h2>
  
  <p>I am not saying that the <code>expected</code> image is what I expect to get from <code>BlendMode.difference</code>, but I want to know how I can get the <code>expected</code> output, i.e. how I achieve only drawing what is different between two images.<br>
  This means that I want to only render <em>pixels from <code>imageB</code> that are <strong>different</strong> from <code>imageA</code></em> and otherwise nothing, i.e. alpha value 0.</p>
  
  <h2>Explanation</h2>
  
  <p>I will try to explain it a bit more clearly again:</p>
  
  <ul>
  <li><p>If the color is the same, draw transparent pixel (remove source pixel).</p></li>
  <li><p>If the color is different, draw destination pixel.</p></li>
  </ul>