Chris West

ES6 – Convert To Integer

There are various ways to convert a string or a floating point number to an integer in JavaScript, but not all of them may suit your needs. In this post we will examine four different ways and then we will see which is the best in all cases.

Solution #1: ~~x

If we are dealing with smaller number then we can leverage bit-wise operators such as bit-wise negation (~). The reason we can only use this solution for smaller numbers is because bit-wise operations can only be executed on a number in the range of -(231) to 231 - 1. If the number is outside of that range it will be converted to a number within that range (eg. -2147483649 becomes 2147483647 and 2147483648 becomes -2147483648).

Solution #2: parseInt(x, 10)

There is actually a function that will convert strings into numbers called parseInt(). We can use this function and specify the base to ensure that numbers starting with 0 will not be parsed as octals (eg. parseInt('010') produces 8 in older versions of ECMAScript).

Solution #3: +parseFloat(x, 10).toFixed(0)

We can also use the equivalent function to parseInt() for floats which is parseFloat(). After that we can use Number.prototype.toFixed() to make the number a string representation of the truncated number. Finally we can prefix this expression with a plus sign (+) to convert the string to a number again.

Solution #4: Math.trunc(x)

We can use the newer Math.trunc() function which should in theory just do what we want 😆 .

Results

Below are the results of using your browser to test out each solution:

    Conclusion

    If you have looked through the results above on a modern browser (one implementing Math.trunc()) you’ll notice that for all of our test cases, it is the only solution that works for them all. Therefore, if you are looking to convert floating-point numbers to integers or strings to integers, the most convenient and straightforward way may in fact be ES6’s new Math.trunc() function. Let me know what you think and as always, happy coding! 😎

    CSS – Local File System Paths On Windows

    When working with Windows you probably have noticed that local file paths use the backslash as the path separator. Although this is the case, even on Windows, in CSS you can use the forward-slash as a path separator to reference an image. If you want to use the forward-slash though, you must escape it with another backslash. Here are two examples:

    #elem1 {
      background-image: url("relative-path\\to\\file.ext");
    }
    #elem2 {
      background-image: url("C:\\path\\to\\file.ext");
    }
    #elem3 {
      background-image: url("relative-path/to/file.ext");
    }
    #elem4 {
      background-image: url("C:/path/to/file.ext");
    }
    

    As you can see above I have three different ways to add a background image:

    1. url("relative-path\\to\\file.ext")
      For the element of ID “elem1” I am specifying that the background image is found at the relative path of “relative-path\to\file.ext”. It is important to note that I am escaping the backslashes (path separators) with an additional backslash.
    2. url("C:\\path\\to\\file.ext")
      Just as in the previous example, if we need to reference something using an absolute path while maintaining backslashes as path separators, we need to escape all backslashes with a preceeding backslash.
    3. url("relative-path/to/file.ext")
      For the element of ID “elem2” I am specifying that the background image is found at the relative path of “relative-path/to/file.ext”. Even though the normal path separator on Windows is a backslash you can use a forward slash.
    4. url("C:/path/to/file.ext")
      Just as in the previous example, if we need to reference something using an absolute path we can use a forward slash as the path separator.

    This may seem like a minor issue but when developing Electron apps it may come in handy. Have fun and as always, happy coding! 😎

    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! 😎