JavaScript – Create Gradient Image Using Canvas

The <canvas> can be quite useful, especially if you want to modify how images look on your site. For example, if you want to make an image appear as a gradient starting at the top with an alpha of 0 and then linearly fading to the image’s full alpha value you can use JavaScript along with the <canvas>:

  1. Make Sure The Image Is On Your Domain

    If the image that you are trying to modify is not on your site’s domain you will not be able to modify it using the canvas unless the image is CORS enabled or unless you are pulling the image via an <input type="file">.
  2. Create the Canvas & Add the Image To It

    var image = document.getElementById('id_of_image');
    var canvas = document.createElement('canvas');
    canvas.width = image.width;
    canvas.height = image.height;
    var context = canvas.getContext('2d');
    context.drawImage(image, 0, 0);
    
  3. Retrieve & Modify Alpha Values

    The canvas’ 2D context object provides a function called getImageData() which will return another object. This object’s data property is an array of the rgba values that make up the image. In other words, the first four values in the array represent the top-most and left-most pixel in the image while the second four values represent the next pixel going from left-to-right and top-to-bottom. Since we want to create a fading gradient effect we need to determine the y value at all times to then figure out the alpha which will depend on the maxY value. NOTE: the alpha value ranges from 0 to 255.
    var imageData = context.getImageData(0, 0, image.width, image.height);
    var d = imageData.data;
    var maxY = image.height;
    for (var y, alpha, i = 3, l = d.length; i < l; i += 4) {
      y = Math.floor(i / 4 / image.width);
      alpha = Math.round(255 * y / maxY);
      d[i] = Math.min(d[i], alpha);
    }
    
  4. Reset Canvas & Set Updated Image Data

    Since we have played around with the alpha values we don't want to simply draw the image data on top of the canvas. Instead we need to clear that canvas and then draw the updated image:
    context.clearRect(0, 0, image.width, image.height);
    context.putImageData(imageData, 0, 0);
    
  5. Use Canvas Data URL As Image's Source

    The canvas has a handy function called toDataURL() which among other things can be used to pull a PNG version of our image which will preserve the transparency. All we need to do is assign this data URL to image's src property and then we are done:
    image.src = canvas.toDataURL();
    
  6. Try It Out

    Feel free to try this code out on your site or you can see how it all works together by using the button below to choose an image to convert to a gradient. After the image is created you should be able to click on it to open it up in a new tab.
So now you may be wondering how the above example works, right? Click here to see the source code. Of course, that is only a very brief example of what you can do. Just as this post from the maker of watermark.js inspired me, I am sure that you can think of many more ways to use the canvas to add amazing effects to your images. As always, feel free to make the code your own. Happy coding! 😎

JavaScript – Use Canvas To Watermark Images

Did you know that you can add a watermark to all of your images that are on the same domain as your site just using JavaScript? Thanks to the <canvas> we can modify images and present in various ways as if they were originally available that way all via JavaScript. The following function is a quick-and-dirty example of how to leverage the canvas to add a watermark to an <img>:

Now let’s use this watermarkImage() function on an image found under the same domain:

Original Watermarked

By using the code below we end up getting the watermarked image above on the right showing the neighborhood of Ensanche Espaillat (Santiago de los Caballeros, Dominican Republic):

var elemImg = document.getElementById('imgToWatermark');
watermarkImage(elemImg, 'Ensanche Espaillat');

Of course, this simple function is not a fully featured solution for adding watermarks to our images. For example the following cases may occur:

  • We just want to create a watermarked image from an image URL.
  • We want to change the background color of the watermark.
  • We want to use a logo image as the watermark.
  • etc., etc.

If the watermarkImage() function works the watermark will be added to the image, but if not the image will not be changed. This is done on purpose to avoid strange behaviour on failure. There are two main reasons why this would fail:

  1. The image you want to watermark is not under the same domain as the page running the JavaScript code.
  2. The browser running the code doesn’t support adding images and/or SVGs to a <canvas>.

There is actually a great solution out there called watermark.js which will probably provide all of the options that you need to watermark your images.

Of course, if you would like to write your own code, my gist at the beginning of this post should be a pretty good start. Have fun and happy coding! 😎

JavaScript Snippet – Get Video Frame As An Image

Lately I have dedicated a little more time to developing an electron app which saves a frame of every video it encounters as PNG images:

JW Videos with images captured via a video element and a canvas element.
JW Videos with images captured via a video element and a canvas element.

Believe it or not the code to turn a frame of a video into an image element is not terribly complicated. Below is a simple function that can be used to get the an image element corresponding to a specific frame in a video:

This getVideoImage() function takes three arguments:

  1. path {string}:
    The path to the video. In the case that you are using this code in a web page this must be a video within the same domain.
  2. secs {number | function(duration): number}:
    If this is a non-negative number this will indicate the time of the frame to capture in seconds. If this is a negative number this will indicate the time of the frame from the end of the video to capture in seconds. If this is a function it will be passed the duration as a number and the return value should be a number (positive or negative) which indicates the time of the frame that should be captured.
  3. callback {function(img, currentTime, event)}:
    The function which is called either after loading the frame’s image successfully or after getting an error. The first argument passed will be the Image object that is created (if no error occurred). The second argument passed will be the actual time in seconds used to pull the frame’s image (if no error occurred).
    The third argument will either be a seeked event or an error event.

This function can be used as is or can be modified. It is important to note that unless the video is in the exact same domain as the web page this code will NOT work due to the canvas being tainted. You can paste the following code into the code editor on this W3Schools sandbox page to see an example of getting multiple frames:

Let me know if you have any questions or suggestions and as usual, enjoy the free code! 😎