ASP.NET Web Greeting Card Tool

img src from Designed by wallpapershd

Introduction

Wishing you all a very Happy Pongal and Makara Sankrathii.

In my previous article,

I explained about how to create a web based Photo editing tool. In this article we will see how to create a web based Greeting Card tool using ASP.NET and jQuery.

This article shows the details of how to do the following.

  1. Clear Card: Clear the card to design new.
  2. Add Image: Upload Image to Canvas Tag (You can add any image to create your Greeting Card).
  3. Add Sticker: Add stickers, for example balloon, flowers, and so on to our Greeting Card for decoration.
  4. Select Color: The selected color can be applied to Card Border and Text.
  5. Add Border: Add a border to the Greeting Card.
  6. Card Title: Add Greeting Card Title. For example, “Happy New Year”.
  7. Card Message: You can add your own wishes to the Greeting card.
  8. Save and Send to Email: The final created Greeting Card can be saved to the application root folder. Also, send the card to a user entered email address.
  9. Post Canvas Greeting Card to Facebook. The Final Edited Greeting Card can be posted to Facebook.
Prerequisites

Visual Studio 2015: You can download it from here.

Using the code

The main purpose is to make the program very simple and easy to use. All the functions have been well commented in the project .Here we will see the procedure to create a Web Greeting Card tool using a HTML 5 canvas.

HTML5

HTML5 is the new version of HTML. HTML5 has cross-platform support. That means HTML5 can work on a PC, Tablet and a Smartphone. HTML5 should be started with a DOCTYPE, for example:

Some of the new features in HTML5 are CANVAS, AUDIO, and VIDEO and so on.

CANVAS

CANVAS is the element for 2D drawings using JavaScript. The Canvas has methods such as drawing paths, rectangles, arcs, text and so on. The Canvas element looks like the following.

  1. <canvas id="canvas" width="400" height="400"></canvas>    
Reference for HTML5 canvasThe Canvas is nothing but a container for creating graphics. To create 2D graphics we need to use JavaScript. We will see the details here in the code.

Create your Web Application in Visual Studio 2015

After installing our Visual Studio 2015 click Start, then Programs and select Visual Studio 2015 - Click Visual Studio 2015. Click New, then Project, select Web and select ASP.NET Web Application. Enter your Project Name and click OK.


 Select Web Forms and click OK.


Now our web application has been created. Add all script and image files needed for this project.

JavaScript Declaration Part

Firstly, add all the JavaScript references and styles to your ASP.NET page as in the following:

  1. <meta http-equiv="Page-Enter" content="blendTrans(Duration=0.0)" />  
  2. <meta http-equiv="Page-Exit" content="blendTrans(Duration=0.0)" />  
  3. <meta http-equiv="x-ua-compatible" content="IE=9" />  
  4.     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript">  
  5.     </script>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  7.     <script type="text/javascript" src="Scripts/jquery-1.10.2.min.js">  
  8.     </script>  
  9.     <script type="text/javascript" src="Scripts/jscolor.js">  
  10.     </script>  

Declare all the variables necessary for Greeting Card Tool. In each declaration I have added comments to explain its usage. 

  1. <SCRIPT>  
  2.     //public Canvas object to use in all the functions.  
  3.   
  4.     //Main canvas declaration   
  5.     var canvas;  
  6.     var ctx;  
  7.   
  8.     var canvasEffect;  
  9.     var ctxEffect;  
  10.     var x = 75;  
  11.     var y = 50;  
  12.     //Width and Height of the canvas  
  13.     var WIDTH = 200;  
  14.     var HEIGHT = 252;  
  15.     //    var dragok = false;  
  16.     //Global color variable which will be used to store the selected color name.  
  17.     var Colors = "";  
  18.     var newPaint = false;  
  19.     var DrawingTypes = "";  
  20.   
  21.     //Circle default radius size  
  22.     var radius = 30;  
  23.     var radius_New = 30;  
  24.     var stickerWidth = 40, stickerHeight = 40;  
  25.     // Rectangle array  
  26.     rect = {},  
  27.     //drag= false defult to test for the draging  
  28. drag = false;  
  29.   
  30.     // Array to store all the old Shanpes drawing details  
  31.     var rectStartXArray = new Array();  
  32.     var rectStartYArray = new Array();  
  33.     var rectWArray = new Array();  
  34.     var rectHArray = new Array();  
  35.   
  36.   
  37.     var recttextXArray = new Array();  
  38.     var recttextYArray = new Array();  
  39.     var recttextWArray = new Array();  
  40.     var recttextHArray = new Array();  
  41.   
  42.     var textXArray = new Array();  
  43.     var textYArray = new Array();  
  44.   
  45.     
  46.     var rectColor = new Array();  
  47.     var DrawType_ARR = new Array();  
  48.     var radius_ARR = new Array();  
  49.   
  50.     var Text_ARR = new Array();  
  51.     var Text_ARRNew = new Array();  
  52.     // Declared for the Free hand pencil Drawing.  
  53.     var prevX = 0,  
  54.     currX = 0,  
  55.     prevY = 0,  
  56.     currY = 0;  
  57.   
  58.   
  59.     //to add the Image  
  60.     var ImageNames = new Array();  
  61.     var imageCount = 0;  
  62.     var imageObj = new Image();  
  63.     var imageObj_BG = new Image();  
  64.     //to clear the Canvas  
  65.     function clear() {  
  66.         ctx.clearRect(0, 0, WIDTH, HEIGHT);  
  67.     }  
init() Method

init is important since for each button click this function will be called and pass the parameter for each function type. In this method I will create an object for the canvas and this canvas object will be used in all other functions. Here for example the DrawType will be DrawImage, DrawText, DrawBorder, Place Uploaded Image as Background and the ImageName parameter will be used to pass each sticker image name and so on. In this init method I will create Mouse events such as Mousedown, Mousemove and MouseUp to add a sticker, move a sticker, resize a sticker and so on.
 
  1. //Initialize the Canvas and Mouse events for Canvas    
  2. function init(DrawType, ImageName)  
  3. {  
  4.     newPaint = true;  
  5.     canvas = document.getElementById("canvas");  
  6.     ctx = canvas.getContext("2d");  
  7.     canvasEffect = document.getElementById("canvas");  
  8.     ctxEffect = canvasEffect.getContext("2d");  
  9.     x = 5;  
  10.     y = 5;  
  11.     if (ImageName)  
  12.     {  
  13.         ImageNames[imageCount] = ImageName;  
  14.         imageCount = imageCount + 1;  
  15.     }  
  16.     DrawingTypes = DrawType;  
  17.     if (DrawType = 'BG')  
  18.     {  
  19.         ctx.drawImage(imageObj_BG, 1, 1, canvas.width - 1, canvas.height - 1);  
  20.     }  
  21.     radius = 30;  
  22.     radius_New = radius;  
  23.     canvas.addEventListener('mousedown', mouseDown, false);  
  24.     canvas.addEventListener('mouseup', mouseUp, false);  
  25.     canvas.addEventListener('mousemove', mouseMove, false);  
  26.     return setInterval(draw, 10);  
  27. // This is just a sample script. Paste your real code (javascript or HTML) here.  
  28. if ('this_is' == /an_example/)  
  29. {  
  30.     of_beautifier();  
  31. }  
  32. else  
  33. {  
  34.     var a = b ? (c % d) : e[f];  
  35. }  
Add Image to canvas

 
In file onchange event we get an Image uploaded by user. We pass this uploaded image to be set as our Canvas Background to design our Greeting Card.
  1. <input type="file" accept="image/*" onchange="uploadImage(event)" />  
  2. // to upload the image to Canvas  
  3.     var uploadImage = function (event) 
  4. {  
  5.         var reader = new FileReader();  
  6.         ////canvas = document.getElementById("canvas");  
  7.         ////ctx = canvas.getContext("2d");  
  8.         reader.onload = function () 
  9.         {  
  10.             imageObj_BG.src = reader.result;  
  11.             init('BG', '');  
  12.             // ctx.drawImage(imageObj_BG, 2, 3, canvas.width - 6, canvas.height );  
  13.         };  
  14.         reader.readAsDataURL(event.target.files[0]);  
  15.  };  
Add Border/Title/Sticker

In the Border Image click event we passed the DrawType as "Border" and in the mouse move event we will call the draw() method. This method depends on the DrawingTypes selected. We will add the features to the canvas tag, for example if
Border is selected then we will draw the border for the canvas tag. If Images is selected then we will add the selected sticker image to the canvas tag.
  1. //Darw all Shaps,Text and add images     
  2. function draw()  
  3. {  
  4.     ctx.beginPath();  
  5.     Colors = document.getElementById("SelectColor").value;  
  6.     ctx.fillStyle = "#" + Colors;  
  7.     switch (DrawingTypes)  
  8.     {  
  9.         case "Border":  
  10.             ctx.strokeStyle = "#" + Colors;  
  11.             ctx.lineWidth = 10;  
  12.             ctx.strokeRect(0, 0, canvas.width, canvas.height)  
  13.             DrawBorder = "YES";  
  14.             //     ctx.rect(canvas.width - 4, 0, canvas.width - 4, canvas.height);    
  15.             break;  
  16.         case "Images":  
  17.             imageObj.src = ImageNames[imageCount - 1];  
  18.             ctx.drawImage(imageObj, rect.startX, rect.startY, rect.w, rect.h);  
  19.             //  ctx.drawImage(imageObj, rect.startX, rect.startY, stickerWidth, stickerHeight);    
  20.             break;  
  21.         case "DrawText":  
  22.             = '54pt Calibri';  
  23.             ctx.fillText($('#txtInput').val(), drawx, drawy);  
  24.             break;  
  25.         case "DrawTextNew":  
  26.             = '16pt Calibri';  
  27.             ctx.fillText($('#txtmsg').val(), drawx, drawy);  
  28.             break;  
  29.     }  
  30.     ctx.fill();  
  31.     // ctx.stroke();    
  32. }  
Save and Send Email

In the send email button client click, we will store the Canvas as image to the hidden field. 

  1. <asp:Button ID="btnImage" runat="server" Text="Send Email"     
  2.              OnClientClick = "sendEmail();return true;" onclick="btnImage_Click" />    
  3.       
  4.  function sendEmail() {    
  5.     var m = confirm("Are you sure to Save ");    
  6.     if (m) {    
  7.     
  8.         var image_NEW = document.getElementById("canvas").toDataURL("image/png");    
  9.         image_NEWimage_NEW = image_NEW.replace('data:image/png;base64,', '');    
  10.         $("#<%=hidImage.ClientID%>").val(image_NEW);    
  11.         alert('Image saved to your root Folder and email send !');    
  12.     }    
  13.     
  14. }  
In the code behind button click event we will get the hidden field value and store the final result image to the application root folder. This image will be used to send an email. 
  1. protected void btnImage_Click(object sender, EventArgs e)  
  2.         {  
  3.             string imageData = this.hidImage.Value;  
  4.             Random rnd = new Random();  
  5.             string imagePath = HttpContext.Current.Server.MapPath("Shanuimg" + rnd.Next(12, 2000).ToString() + ".jpg");  
  6.             using (FileStream fs = new FileStream(imagePath, FileMode.Create))  
  7.             {  
  8.                 using (BinaryWriter bw = new BinaryWriter(fs))  
  9.                 {  
  10.                     byte[] data = Convert.FromBase64String(imageData);  
  11.                     bw.Write(data);  
  12.                     bw.Close();  
  13.   
  14.                     sendMail(imagePath);  
  15.                 }  
  16.             }  
  17.         }  
In the button click event after the image is saved to the root folder, we will send the image path to the sendMail method. In this method using the user entered From and To email address we will send the Greeting Card with the subject and message to the email. 
  1. private void sendMail(string FilePath)  
  2.         {  
  3.             MailMessage message = new MailMessage();  
  4.             SmtpClient smtpClient = new SmtpClient();  
  5.             string msg = string.Empty;  
  6.             try  
  7.             {  
  8.                 MailAddress fromAddress = new MailAddress(txtFromEmail.Text.Trim());  
  9.                 message.From = fromAddress;  
  10.                 message.To.Add(txtToEmail.Text.Trim());  
  11.   
  12.                 message.Attachments.Add(new Attachment(FilePath));  
  13.   
  14.                 message.Subject = txtSub.Text.Trim();  
  15.                 message.IsBodyHtml = true;  
  16.                 message.Body = txtMessage.Text.Trim();  
  17.                 smtpClient.Host = "smtp.gmail.com";  
  18.                 smtpClient.Port = 587;  
  19.                 smtpClient.EnableSsl = true;  
  20.                 smtpClient.UseDefaultCredentials = true;  
  21.                 smtpClient.Credentials = new System.Net.NetworkCredential(userGmailEmailID, userGmailPasswod);  
  22.   
  23.                 smtpClient.Send(message);  
  24.                 msg = "Successful<BR>";  
  25.             }  
  26.             catch (Exception ex)  
  27.             {  
  28.                 msg = ex.Message;  
  29.             }  
  30.         }  
Here we use the host as smtp.gmail.com and in System.Net.NetworkCredential(userGmailEmailID, userGmailPasswod); you need to provide your Gmail Email address and Gmail password to send the email.

Note: We have declared the variable as global as in the following so that the user can add their own Gmail Email address and Gmail password. 

  1. string userGmailEmailID = "YourGamilEmailAddress";    
  2. string userGmailPasswod = "YourGmailPassword";  

Post Photo to Facebook

To post our photo to facebook we need to a Facebook APPID. To create our APPID go to Facebook Developers and login using your facebook id.
 
After Login to create New App ID enter yourdisplay name and click Create App ID
 
 
Now you can see your App ID has been created.You can use this App ID to post your image to Facebook.
 

Click on Settings and add your website URL in case, if you’re developing as localhost in site URL you can give the localhost URL as below.

 
Click Settings, then Advanced and set the Embedded browser OAutho Login to “YES”
 
Send to FB: Using Facebook API we can pass the Canvas converted base64 Image to Facebook using our App ID. Here is the reference link which explains how to convert and embed HTML5 Canvas 5 Image to base64. 
  1. function sendtoFB() {  
  2.        var m = confirm("Are you sure Post in FaceBook ");  
  3.        if (m) {  
  4.   
  5.   
  6.            $.getScript('//connect.facebook.net/en_US/all.js'function () {  
  7.                // Load the APP / SDK  
  8.                FB.init({  
  9.                    appId: 'YOURFBAPPID'// App ID from the App Dashboard  
  10.                    cookie: true// set sessions cookies to allow your server to access the session?  
  11.                    xfbml: true// parse XFBML tags on this page?  
  12.                    frictionlessRequests: true,  
  13.                    oauth: true  
  14.                });  
  15.                FB.login(function (response) {  
  16.                      
  17.                    if (response.authResponse) {  
  18.                        
  19.                        window.authToken = response.authResponse.accessToken;  
  20.                        
  21.                        PostImageToFacebook(window.authToken)  
  22.                    } else {  
  23.                    }  
  24.                }, {  
  25.                    scope: 'publish_actions'  
  26.                });  
  27.            });  
  28.   
  29.        }  
  30.   
  31.    }  


Similar Articles