____  ___    _  _     _   _ _____     _______
 / ___|/ _ \  | || |   | | | |_ _\ \   / / ____|
| |  _| | | | | || |_  | |_| || | \ \ / /|  _|
| |_| | |_| | |__   _| |  _  || |  \ V / | |___
 \____|\___/     |_|   |_| |_|___|  \_/  |_____|

 --- A GOPHER-LIKE INTERFACE FOR HIVE BLOCKCHAIN ---

Creating Dynamic Cards using Angular JS

BY: @chri5h | CREATED: June 23, 2018, 4:28 p.m. | VOTES: 25 | PAYOUT: $62.76 | [ VOTE ]

Repository: https://github.com/angularjs

What will I Learn?

In this tutorial, you will learn the following

Requirements

For this tutorial, you will need the following

Difficulty

Tutorial Content

> Angular JS framework which operates exactly as Javascript, makes coding more simplified and easy to use with other programming languages.

> Angular JS framework can be used to achieve variety of functionality and gives user more options and flexibility in implementing their designs and functionalities.

We might already know how to use the HTML Canvas using JavaScript but we intend using Angular JS framework for speed and efficiency. In this tutorial we intend creating dynamic ID card that can be generated by staffs of an organization.

Step 1: Getting Started

For this tutorial, we need to design a template of the ID card carrying fixed element contents for example:

The fixed elements are contents of the ID card that are not meant to change from one staff/user to another.

[IMAGE: https://cdn.steemitimages.com/DQmdEW6nVZdRsTFUT89qP8ZXintN8niQKx2FifNjXenCsE9/template.png]

[IMAGE: https://cdn.steemitimages.com/DQmUP1Koeoof8FbYKju1vP1CGmuGDjuGzLuzfYtpD9Lfv9T/Sample.png]

You can design your own ID card template using any design tool that you are familiar with and then export the design as either PNG (Portable Network Graphics) or JPEG (Joint Photograph Export Group). But for this project I exported my design as PNG (Portable Network Graphics). A sample of my ID card template is located in assets/img/patterns/template.png and the complete preview is located in assets/img/patterns/sample.png. Those can serve as a guide in designing your own card temple for this tutorial.

Step 2: Starting out template

To begin, we start with the default html template with the head and body tags. We link all necessary script files within the head tag, including our angularjs script. We also need another JS file called app.js where all our angular implementation details will be performed and also another JS script file for Javascript implementation details.

index.html





    Bussiness Design





















> Note: Our index.html file contains some new attributes within the html tag and another within the body tag.
>
> - ng-app="myApp" is an angular directive that triggers angular js to function with the HTML DOM that it covers. It tells angular JS the area of the HTML to take charge of.
> - ng-controller="MainCtrl" is an angular controller created within the angular script app.js for manipulation of a particular area of the HTML DOM.

app.js

(function (){

  var app = angular.module('myApp', []);

  app.controller('MainCtrl', ['$scope', function($scope) {


  }]);


}());

We first have to create a directive in our blank app.js script file which allows us create a controller which is in-charger of a particular area of our html file. To create a directive, you call the angular.module() which requires the following parameters;

The controller is then built based on the app directive that has been created earlier. We begin the controller with a controller name MainCtrl, a single dependency $scope and then a function with $scope as the only parameter of the function.

NOTE: The $scope parameter can be accessed anywhere within the confines of the MainCtrl controller in the html. Our script.js file will be blank for the mean time and check your console to find out if we have any errors generated before proceeding to the next step.

Step 3: HTML Canvas

The HTML Canvas is an element which is used to draw graphics on a web page, We learn to utilize it better by drawing multiple graphics within the canvas element, including text. We want to create a canvas that draws the template into the canvas. For the design of the site, we will be using bootstrap.






Sample Preview and Canvas







            Upload Image



Within the body tag, we have in container that holds two separate columns. One carries the sample image and the other the canvas element where we will be drawing the template for further manipulations.

[IMAGE: https://cdn.steemitimages.com/DQmTjGwuti5f2Ek5nYKKQWAYnC6af56x1GT5tVDc5JF4oHQ/Sample%20and%20Canvas.JPG]

app.js

$scope.draw = function draw () {
    //Draw canvas
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext("2d");
    // Create Objects
    var imageObj = new Image();
    // Declare objects sources
    imageObj.src = 'assets/img/patterns/template.png';
    // Specify Width and height of each object
    var width = 555.753;
    var height = 344.471;
    // Draw the image objects into the canvas
    imageObj.onload = function() {
    context.drawImage(imageObj, 0, 0, width, height);
    }
};

When the button is clicked, angular executes the draw() to draw the template to the canvas we have created within the HTML tag.

js context.drawImage(imageObj, hPoint, vPoint, width, height);

[IMAGE: https://cdn.steemitimages.com/DQmTkbHTE1j47kdBUpaU2igRCTqUWADwxXsGWkaDHq2utxt/Canvas%20Image.JPG]

Step 4: Draw Uploaded Image on Canvas

The template design and sample design now looks similar, but the only difference is the image of the staff, name and other details below the staff image. We will modify our code snippet so we can upload different images and draw the image to the canvas.

First we will remove the previous upload button, and create a new section that will house the upload button which will re-implemented to upload the selected image and then draw the image on the canvas at our specified position.






Upload Image Section





            Upload Image



<

Also we need to add the following JavaScript event to help fix the image to the clock div and as well upload the image to the image tag with id="imageP" so we can pick the image source for upload to the canvas.

[IMAGE: https://cdn.steemitimages.com/DQmaqEe62YwhkPD3Sgj8k7FFXoJgSRB4sbm6hthaPE78Kdc/upload%20preview.JPG]

> The code snippet can be added below the body tag.


    $("#details").hide();
    $("#final").hide();
    function readURL(event){
        var getImagePath = URL.createObjectURL(event.target.files[0]);
        $('#clock').css('background-image', 'url(' + getImagePath + ')');
        $("#imageP").attr('src', getImagePath);
        $('#imageUploadBtn').css("display", "none");
    }

Note: This script executes on when the value of the input file type changes using the jquery onchange().

app.js

$scope.draw = function draw () {

    var x = $("#imageP").attr('src');
    //Draw canvas
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext("2d");
    // Create Objects
    var imageObj = new Image();
    var imageObj_01 = new Image();
    var imageObj_02 = new Image();
    // Declare objects sources
    imageObj.src = 'assets/img/patterns/template.png';
    imageObj_01.src = x;
    imageObj_02.src = 'assets/img/patterns/Logomask.png';
    // Specify Width and height of each object
    var width = 555.753;
    var height = 344.471;
    var width1 = 133;
    var width2 = 57;
    var height1 = 130.6;
    var height2 = 49;
    // Draw the image objects into the canvas
    imageObj.onload = function() {
        context.drawImage(imageObj, 0, 0, width, height);
        context.drawImage(imageObj_01, 339.5, 82, width1, height1);
        context.drawImage(imageObj_02, 373, 195, width2, height2);
    }

    $("#upload").hide();
    $("#details").show();

};

NOTE: The upload button looks similar to the previous one, but the difference is that we added new objects to be drawn to the canvas at various positions.

[IMAGE: https://cdn.steemitimages.com/DQmVeeRL53yuvyyG6vVEanTG7UmjrUsG4cJbCLhNjYYuEYu/uploaded%20preview.JPG]

Step 5: Add the text to the Design

Including the text at various positions of the canvas is actually implemented same way we implement the positioning of graphics or objects on the canvas. We get the text from users as we tend to allow the template content to be dynamic based on the user details. We use HTML form to collect the details and use the angular ng-model directive for two-way data-binding. We also needed to limit the number of characters per input fields.

Then when the form is submitted, we invoke the angular function called submitWriteUp and pass in the form details as parameters (using angular two-way binding) of the function so we can draw each form detail on the already created canvas myCanvas.

index.html










Enter Required Details




                        Name:




                        Position:




                        Phone:




                        Email:




                        Website:




                        Submit Details






[IMAGE: https://cdn.steemitimages.com/DQmNMSZsMhiftAzM21p1aYc8jcsVqKzjR5q2ePfmTAcah7y/form%20preview.JPG]

When the form is submitted and we receive the form details, we will draw the details on the canvas at various position based on your design. The steps to drawing the text are as follows:

> Note: The vPoint and hPoint can always very based on your template design so you tend to change the values and preview if it matches your desire else continue to change the value of the points.

app.js

$scope.submitWriteUp = function (name, position, phone, email, website) {

    var canvas = document.getElementById('myCanvas');

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

    var middle = canvas.width/2;

    context.font = "19px ExoRegular";
    context.fillStyle = "#fff";
    context.textAlign = "center";
    context.fillText(name, middle+130, 40);
    // Other  writeups drawn with different style
    context.font = "17px ExoRegular";
    context.fillText(position, middle+130, 60);
    context.font = "12px ExoRegular";
    context.fillText(phone, middle+150, 264);
    context.fillText(email, middle+139, 288);
    context.fillText(website, middle+142, 313);
};

$scope.submitWriteUp();
$("#final").hide();

> Note: To specify new fonts, style and textAlign for different details, you need to specify the values of this parameters before drawing the text.

[IMAGE: https://cdn.steemitimages.com/DQma835seh71yN98sQP59vrJYRFuHiPxskZqbnBgdoUBcsR/textPreview.JPG]

Step 6: Download the Canvas as image

The final step is to download the generated image within the canvas. One simple way is for the user to right click on the canvas and select "save image as" and select a location where it will be saved and the image will be download.

But we want to hide the form details and display a final preview of the image with a button to download the image by clicking on the button. So we can add some code snippet within the submitWriteUp scope function so that we can attach the image to a final and the button for it to be downloaded.

So we create a new section with an id, within it is a div with id="finalPreview" to hold the final image and then a button for downloading the image with id="download".

index.html


















We need to modify our submitWriteUp scope to append the image within the canvas to the finalPreview div and also the href of the download button. We will add the code snippet below within the submitWriteUp scope function.

app.js

    img.src = canvas.toDataURL();
    var src = canvas.toDataURL();
    var image = '';
    $('#download').attr('href', src);
    $('#finalPreview').prepend(image);
    $("#final").show();
    $("#details").hide();

> Note:
>
> - Line 1 and 2 converts the image within the canvas to a URL which hold the image data.
> - Line 3 we create an image which will be appended to finalPreview as a preview of the canvas image.
> - Then the source src of the image is added as the href of the download button for download.
> - Then we can now hide the details section and display the final section with the download button.

[IMAGE: https://cdn.steemitimages.com/DQmTSkoh7oQDnRA6UB75rNkP8PKFeyJhXYEyb4s9fGhhsAh/DownloadOption.JPG]

SAMPLE PREVIEW OF THE DOWNLOADED IMAGE

[IMAGE: https://cdn.steemitimages.com/DQmXNHAs6URV3gMPqfcq41XrcUMJJVKJHEJb1cC9iQRUU4U/steemjet%20(2).png]

> Please uncomment all image tags within the code snippets when using them because while uploading this post, I had image upload conflicts. Thanks

Check out full code snippet for this step in index.html, app.js and main.css.

Video of Work Done

[IMAGE: https://cdn.steemitimages.com/DQmaw8W3r6jgaNe8z9iz66a8rme9eQdqYz8CfoH6rqNyAV3/ezgif.com-video-to-gif.gif]

Previous Tutorials

-

-

Proof of Work Done

I hope you find this tutorial very useful and you can access the complete code for this tutorial in the github repo.

TAGS: [ #utopian-io ] [ #tutorials ] [ #angularjs ] [ #github ]

Replies

@josephace135 | June 24, 2018, 8:34 a.m. | Votes: 3 | [ VOTE ]

Hi @chri5h,

You have a great tutorial and I just found out a part in your code especially in Step 3: HTML Canvas; as seen in the screenshot below:
[IMAGE: https://cdn.steemitimages.com/DQmPGbACuduDowL43rycVvhtru3a6MR81SZGGXmsQzcj5hD/blob]
In line 3, it should be ended with instead of, though it is just some sort of cosmetics error, this breaks the DOM structure as per @mcfarhat.

Additionally, in Step 4: Draw Uploaded Image on Canvas, you've mentioned about onchage()? Is it onchange()?

@chri5h | June 24, 2018, 9:52 a.m. | Votes: 1 | [ VOTE ]

Hi @josephace135,

Thanks for the correction, it was some syntax error and the other one is onchange() not onchage().

Corrections has been effected. Thanks

@josephace135 | June 24, 2018, 1:36 p.m. | Votes: 0 | [ VOTE ]

You're welcome @chri5h. My pleasure to help :)

@utopian-io | June 27, 2018, 9:23 a.m. | Votes: 0 | [ VOTE ]

Hey @josephace135
Here's a tip for your valuable feedback! @Utopian-io loves and incentivises informative comments.

Contributing on Utopian
Learn how to contribute on our website.

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

@steemitboard | June 25, 2018, 3:13 p.m. | Votes: 0 | [ VOTE ]

Congratulations @chri5h! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

[IMAGE: https://steemitimages.com/70x80/http://steemitboard.com/notifications/votes.png] Award for the number of upvotes

Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @steemitboard!

Participate in the SteemitBoard World Cup Contest!
Collect World Cup badges and win free SBD
Support the Gold Sponsors of the contest: @good-karma and @lukestokes

> Do you like SteemitBoard's project? Then Vote for its witness and get one more award!

@yokunjon | June 27, 2018, 11:05 a.m. | Votes: 1 | [ VOTE ]

I thank you for your contribution. Here are my thoughts;

  • Normally, I don't like tutorials focused on examples about content creation. But, as this is a good example of how to create a unique project, I gave it a higher score. So I suggest keeping your examples high quality and unique like this.

  • There are several punctuation and structure mistakes in your paragraph. Still, even it's understandable, if you can avoid, it would be better.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.

Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

@chri5h | June 27, 2018, 11:39 a.m. | Votes: 3 | [ VOTE ]

I am grateful @yokunjon for your review and thoughts, I will continue in my possible best to improve to be at my best practices.

@utopian-io | June 27, 2018, 6:40 p.m. | Votes: 1 | [ VOTE ]

Hey @chri5h
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

[ BACK TO TRENDING ] [ BACK TO MENU ]
CMD>