title: How to crop image diagonally in canvas
body: <p>I'm trying to crop image to selected red rectangle in canvas, but i'm stuck. Do you have any idea?</p>
  
  <p>I have data about coords rectangle and vertex, and i can calculate it to pixels. </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>let arr = [
    [2333748.391245694, 6846480.395930305],
    [2343351.375319867, 6838186.909684428],
    [2339754.200562619, 6834021.75996551],
    [2330151.216488446, 6842315.246211386],
    [2333748.391245694, 6846480.395930305]
  ]
  
  let xmax = 2343351.375319867
  let xmin = 2330151.216488446
  let ymax = 6846480.395930305
  let ymin = 6834021.75996551
  
  const mapWidth = xmax - xmin
  const mapHeight = ymax - ymin
  
  let h = 600;
  let w = 637.0370370370371;
  
  let A = [((arr[0][0] - xmin) * w) / mapWidth, 0]
  let B = [w, ((ymax - arr[1][1]) * w) / mapHeight]
  let C = [((xmax - arr[0][0]) * w) / mapWidth, h]
  let D = [0, ((arr[1][1] - ymin) * w) / mapHeight]
  
  var canvas = document.getElementById('image');
  var context = canvas.getContext('2d');
  var imageObj = new Image();
  imageObj.onload = () =&gt; {
    context.drawImage(imageObj, ...A, ...B, ...C, ...D);
    context.beginPath();
    context.lineWidth = "6";
    context.strokeStyle = "blue";
    context.rect(...A, 5, 5);
    context.rect(...B, 5, 5);
    context.rect(...C, 5, 5);
    context.rect(...D, 5, 5);
    context.stroke();
  };
  imageObj.src = './test.png';</code></pre>
  </div>
  </div>
  </p>
  
  <p><a href="https://i.stack.imgur.com/15BPX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/15BPX.png" alt="test image"></a></p>