There are a couple of use cases for using canvas to optimize, change, resize or just show the user uploads. Since React is our library of choice, let’s dive into how we can create a simple but powerful hook to achieve expected app behavior.

Let us imagine that we are building some sort of web app with React and it happens that our app has a user profile section where users can add cover/profile photos in order to personalize their profiles.

Users, of course, have the ability to import their profile data, and in that case, we need to be able to copy their photos and upload them to our system.

Let’s name our hook** useCanvasImage.js**

First of all, we need to think about creating an actual image element from some URL, either local or an external one.

const createImage = (url) =>
  new Promise((resolve, reject) => {
    const image = new Image();
    image.addEventListener('load', () => resolve(image));
    image.addEventListener('error', error => reject(error));
    image.setAttribute('crossOrigin', 'anonymous');
    image.src = url;
  });

Okay, now when we have this nice util, we can proceed to build our hook.

As we talked about at the beginning, we want to be able to reduce image size and quality. So, let us create a couple of constants as default correction factors.

#programming #react #javascript #front-end-development

How to Use HTML Canvas to Edit Image Uploads with React
1.20 GEEK