This example demonstrates how to encode text into an image using morse code. The text is first converted to morse code, and then each morse character is represented as a set of dots and dashes, where the dot is represented as 0 and the dash as 1. This allows us to have a binary, 8-bit, value for each morse character representation.
- The text is passed to the
morseEncodefunction, which converts the text to morse code using themorseCodeobject. - The resulting morse code is then converted to a hex string representation, where each morse character is represented as two hex digits (e.g. '.' = '2e', '-' = '2d', ' ' = '20').
- An image is loaded into a canvas, and the image data is retrieved using the
getImageDatamethod of the canvas 2D context. - The hex string is split into an array of hex values, and the alpha channel of the image data is updated with these values using a for loop.
- The encoded image data is then drawn on a new canvas element using the
putImageDatamethod of the canvas 2D context.
- Import the
morseEncodeandstringToHexArrayfunctions, and themorseCodeobject from theencoder.jsfile. - Call the
morseEncodefunction with the text you want to encode. - Convert the morse code to hex string representation using
stringToHexArrayfunction. - Create an instance of an image, set the
srcto the image you want to encode, and attach anonloadevent listener to the image. - In the
onloadevent, retrieve the image data using thegetImageDatamethod of the canvas 2D context, and update the alpha channel of the image data with the hex values. - Draw the encoded image data on a new canvas element using the
putImageDatamethod of the canvas 2D context.
Please note that the image must be loaded from the same domain as the script, otherwise the browser will throw a security error.