Use canvas on Ionic for image overlay
Recently for an app i’ve developed, i need to write some text overlay over a camera captured image. For the sake of simplicity on this tutorial we aren’t going to use the camera but we will add the overlay text on a preloaded image. To make it possible in a javascript/Web environment we can use the power of the HTML5 Canvas element.
You can use this element to draw anything on the screen and also save it as image. Our canvas will be off the screen and we will use it to combine the image and the text.
Let’s start create our new Ionic blank application with CLI.
ionic start overlayApp blank
HTML View
First of all we need to define a view for our application. We need just a img element and a input text where write our message to overlay. Modify the index.html as below :
In the view file we also made a button to call the createOverlay fuction, binded the input text to a variable “textOverlay” and made the image source dynamic binded to an AngularJS variable. Now that we have the view of our app in place we can start thinking about the controller.
AngularJS controller
First of all we have to define the controller. Make it in the app.js adding the following lines:
I’ve added a image.jpg in the img folder. Now if you look at the browser where the app is running you will see something like the image below.
In the first part of the controller we defined the variables used by the app to store the image and we take the reference to the canvas and the context of it. Now we have to implement the createOverlay function
The function is very simple. First we set the dimension of the canvas to match the start image, then we draw it inside the canvas using the drawImage function. We don’t need to specify anythings more then the position because the image will fit in the canvas perfectly.
After the image is draw into the canvas we can render the text over it, setting before some style for it. The text position is calculated on the canvas dimension. Half the width and 80% of the height. Once the text is rendered and we have the final image we take it from the canvas with the toDataUrl() function.
An important thing to notice here we didn’t assign the resulting variable to the $scope.image but we have set a timeout function that take 200msec before the assignment. This is necessary because the canvas need time to render the image into data and if we don’t wait we can take the wrong value for the variable.
This short tutorial can be really usefull in case of apps where you want to take a photo and overlay a text on it.
The complete source code can be found on gitHub
0 comments