MAL's Logo

Basic Media Cropping

💡 Implementation of the react-image-crop package and solution to potential canvas issue.

The Issue

As I implemented this library to crop medias in my project, I encountered an issue that I couldn’t find addressed anywhere. Most examples provided allow you to test with an image that you upload from your computer, meaning that security is never an issue.

However, when attempting to download a cropped image that exists in a server somewhere, the following error comes up: Failed to execute 'toBlob' on 'HTMLCanvasElement': Tainted canvases may not be exported. From this error, I learned the following:

  • .toBlobtoDataURL() or captureStream() will throw the above error when it considers the canvas to the tainted
  • The above error can occur when the image has not been provided a crossOrigin parameter
  • Breakdown

    The solution is a two part. On the code, the image needs the crossOrigin="anonymous" parameter (which if you try to console.log in the designCanvasImage function, it is undefined otherwise as default) and the server handling the images has to either whitelist the right domains, or open it to all, i. e. access-control-allow-origin: [whitelist origins] or access-control-allow-origin: *.

    The code:

    <img
      ref={imageRef}
      src={
        "https://ucd14fc47f16984c058b279b72f0.previews.dropboxusercontent.com/p/thumb/ACDn9SdFyOKZRp6EM9Ldyv6tJ0JD0jeQ2_D9McvcqYhhZzXBf1aoSKpfH5WWTVCNRoNv-zJu5AixlgnBZhf9myKgz4I00NrrnqACcpaurKg53Lo7NuN2ZQt0UUu3947dv6h67eTXjxoi9xRqpXhimv9rO0E1L0OUokAm8SuXUz7id9_kIyB9Uvl8uo-yicgvVm25ForHKpcMOnGbrefecnJpBtLbEEdJWymBEafhBuQvhxCb2vmwCsJ-OfWxj-y-9BHbpmBSmd37XXtAb_wN58x-t9pXeAD0BUlWodY9SRPA3mzsTMHKOYzF2mLQ1IFiBLNdtYHqcLeqz8QU3eB1pJBs3pv7Kc5uUd9_FJe6Kx0IMZ-kMHw2toIA_djqMshjBK4/p.jpeg"
      }
      alt="original"
      onLoad={handleImageLoad}
      crossOrigin="anonymous"
    />

    The server response:

    Resources

  • https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image
  • https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement
  • https://www.npmjs.com/package/react-image-crop
  • MAL's Logo© 2021 – 2026 MAL. All rights reserved.