Updating contents inside an image using html5 canvas

Posted By : Arun Kumar | 26-Dec-2014

 A simple way of getting desired content inside the image for every case ,is to create seperate images for every cases and switch accordingly.This way could become very time consuming if we have like hundreds of cases.One solution will be to update the contents using some scripts and html5 canvas tag.

Lets take a look what we are going to achieve.

image to be edited

I am supposed to update this currency (INR) according to the location from which a user is seeing this image.So,what I am going to do is erase this INR from there because that will be printed with the script.

no currency image

The next step is to generate this image using html5 canvas.

<canvas  id="no-buy-ads" width="619" height="443"></canvas>

Thats it with the html part now lets write script for filling this canvas.

      var canvas = document.getElementById('no-buy-ads');

      var context = canvas.getContext('2d');

      var imageObj = new Image();

      imageObj.onload = function() {

        context.drawImage(imageObj, 69, 50);

      };

      imageObj.src = 'assets/no-ads.png';


 by now we have generated the image inside the canvas.Now its turn for placing the currency next to the price inside this image.

        var currency = 'INR';

        var canvas = document.getElementById('no-buy-ads');

        var context = canvas.getContext('2d');

        var imageObj = new Image();

        imageObj.onload = function() {

          context.drawImage(imageObj, 0, 0);

          context.fillStyle = 'rgb( 123, 123, 123 )'; 

          context.font = '10pt Roboto';

          context.fillText(currency, 479, 235);

          context.fillText(currency, 479, 256.5);

        };

        imageObj.src = 'assets/no-ads.png';    

 context.filltext() function is doing the magic here along with context.fillStyle and context.font.First parameter is the string that will be dynamic updated and the next (479,235) are the coordinated where the currency is being outputted.

The output

final output

About Author

Author Image
Arun Kumar

Arun is a creative UI Developer

Request for Proposal

Name is required

Comment is required

Sending message..