ASP.Net Web Greeting Card Tool
You can download the Source Code from this link Download Source Code
Introduction
https://code.msdn.microsoft.com/site/view/file/146118/1/1.gif
Wishing you all a Merry Christmas and Happy New Year.
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.
https://code.msdn.microsoft.com/site/view/file/146119/1/2.PNG
Web Greeting Card Tool Features
- **Clear Card: **Clear the card to design new.
- **Add Image: **Upload Image to Canvas Tag (You can add any image to create your Greeting Card)
- **Add Sticker: **Add stickers, for example balloon, flowers, and so on to our Greeting Card for decoration.
- **Select Color: **The selected color can be applied to Card Border and Text.
- **Add Border: **Add a border to the Greeting Card
- **Card Title: **Add Greeting Card Title. For example like “Happy New Year”
- **Card Message: **You can add your own wishes to the Greeting card.
- **Save and Send to Email: **The final created Greeting Card can be saved to the application root folder and send the Card to a user entered Email address.
- Post Canvas Greeting Card to Facebook. The Final Edited photo can be posted to Facebook.
Prerequisites
Visual Studio 2015 - You can download it from here.
Code Part
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 HTML5 canvas.
HTML5: HTML5 is the new version of HTML. HTML5 has cross-platform support. That means that HTML5 can work in 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 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 as in the following.
Reference for HTML5 canvas.
The 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.
https://code.msdn.microsoft.com/site/view/file/146120/1/3.PNG
Select Web Forms and click ok
https://code.msdn.microsoft.com/site/view/file/146121/1/4.PNG
Now our web application has been created. Add all script and image files needed for this project.** **
JavaScript Declaration Part
First add all the JavaScript references and styles to your ASP.NET page as in the following:
<meta http-equiv="Page-Enter" content="blendTrans(Duration=0.0)" />
<meta http-equiv="Page-Exit" content="blendTrans(Duration=0.0)" />
<meta http-equiv="x-ua-compatible" content="IE=9" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="Scripts/jscolor.js"></script>
Declare all the variables necessary for Greeting Card Tool. In each declaration I have added comments to explain its usage.
<SCRIPT>
//public Canvas object to use in all the functions.
//Main canvas declaration
var canvas;
var ctx;
var canvasEffect;
var ctxEffect;
var x = 75;
var y = 50;
//Width and Height of the canvas
var WIDTH = 200;
var HEIGHT = 252;
// var dragok = false;
//Global color variable which will be used to store the selected color name.
var Colors = "";
var newPaint = false;
var DrawingTypes = "";
//Circle default radius size
var radius = 30;
var radius_New = 30;
var stickerWidth = 40, stickerHeight = 40;
// Rectangle array
rect = {},
//drag= false defult to test for the draging
drag = false;
// Array to store all the old Shanpes drawing details
var rectStartXArray = new Array();
var rectStartYArray = new Array();
var rectWArray = new Array();
var rectHArray = new Array();
var recttextXArray = new Array();
var recttextYArray = new Array();
var recttextWArray = new Array();
var recttextHArray = new Array();
var textXArray = new Array();
var textYArray = new Array();
var rectColor = new Array();
var DrawType_ARR = new Array();
var radius_ARR = new Array();
var Text_ARR = new Array();
var Text_ARRNew = new Array();
// Declared for the Free hand pencil Drawing.
var prevX = 0,
currX = 0,
prevY = 0,
currY = 0;
//to add the Image
var ImageNames = new Array();
var imageCount = 0;
var imageObj = new Image();
var imageObj_BG = new Image();
//to clear the Canvas
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
**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.
//Initialize the Canvas and Mouse events for Canvas
function init(DrawType, ImageName) {
newPaint = true;
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
canvasEffect = document.getElementById("canvas");
ctxEffect = canvasEffect.getContext("2d");
x = 5;
y = 5;
if (ImageName) {
ImageNames[imageCount] = ImageName;
imageCount = imageCount + 1;
}
DrawingTypes = DrawType;
if (DrawType = 'BG') {
ctx.drawImage(imageObj_BG, 1, 1, canvas.width - 1, canvas.height - 1);
}
radius = 30;
radius_New = radius;
canvas.addEventListener('mousedown', mouseDown, false);
canvas.addEventListener('mouseup', mouseUp, false);
canvas.addEventListener('mousemove', mouseMove, false);
return setInterval(draw, 10);
}
Add Image to canvas
**
**
https://code.msdn.microsoft.com/site/view/file/146123/1/2.gif
In file onchange event we get the Image uploaded by user .We pass this uploaded image to be set as our Canvas Background to design our Greeting Card.
<input type="file" accept="image/*" onchange="uploadImage(event)" />
// to upload the image to Canvas
var uploadImage = function (event) {
var reader = new FileReader();
////canvas = document.getElementById("canvas");
////ctx = canvas.getContext("2d");
reader.onload = function () {
imageObj_BG.src = reader.result;
init('BG', '');
// ctx.drawImage(imageObj_BG, 2, 3, canvas.width - 6, canvas.height );
};
reader.readAsDataURL(event.target.files[0]);
};
Add Border/Title/Sticker:
https://code.msdn.microsoft.com/site/view/file/146124/1/3.gif
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.
//Darw all Shaps,Text and add images
function draw() {
ctx.beginPath();
Colors = document.getElementById("SelectColor").value;
ctx.fillStyle = "#" + Colors;
switch (DrawingTypes) {
case "Border":
ctx.strokeStyle = "#" + Colors;
ctx.lineWidth = 10;
ctx.strokeRect(0, 0, canvas.width, canvas.height)
DrawBorder = "YES";
// ctx.rect(canvas.width - 4, 0, canvas.width - 4, canvas.height);
break;
case "Images":
imageObj.src = ImageNames[imageCount - 1];
ctx.drawImage(imageObj, rect.startX, rect.startY, rect.w, rect.h);
// ctx.drawImage(imageObj, rect.startX, rect.startY, stickerWidth, stickerHeight);
break;
case "DrawText":
ctx.font = '54pt Calibri';
ctx.fillText($('#txtInput').val(), drawx, drawy);
break;
case "DrawTextNew":
ctx.font = '16pt Calibri';
ctx.fillText($('#txtmsg').val(), drawx, drawy);
break;
}
ctx.fill();
// ctx.stroke();
}
**Save and Send Email
** In the send email button client click, we will store the Canvas as image to the hidden field.
<asp:Button ID="btnImage" runat="server" Text="Send Email"
OnClientClick = "sendEmail();return true;" onclick="btnImage_Click" />
function sendEmail() {
var m = confirm("Are you sure to Save ");
if (m) {
var image_NEW = document.getElementById("canvas").toDataURL("image/png");
image_NEW = image_NEW.replace('data:image/png;base64,', '');
$("#<%=hidImage.ClientID%>").val(image_NEW);
alert('Image saved to your root Folder and email send !');
}
}
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.
protected void btnImage_Click(object sender, EventArgs e)
{
string imageData = this.hidImage.Value;
Random rnd = new Random();
string imagePath = HttpContext.Current.Server.MapPath("Shanuimg" + rnd.Next(12, 2000).ToString() + ".jpg");
using (FileStream fs = new FileStream(imagePath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);
bw.Write(data);
bw.Close();
sendMail(imagePath);
}
}
}
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.
private void sendMail(string FilePath)
{
MailMessage message = new MailMessage();
SmtpClient smtpClient = new SmtpClient();
string msg = string.Empty;
try
{
MailAddress fromAddress = new MailAddress(txtFromEmail.Text.Trim());
message.From = fromAddress;
message.To.Add(txtToEmail.Text.Trim());
message.Attachments.Add(new Attachment(FilePath));
message.Subject = txtSub.Text.Trim();
message.IsBodyHtml = true;
message.Body = txtMessage.Text.Trim();
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential(userGmailEmailID, userGmailPasswod);
smtpClient.Send(message);
msg = "Successful<BR>";
}
catch (Exception ex)
{
msg = ex.Message;
}
}
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.
https://code.msdn.microsoft.com/site/view/file/146125/1/5.PNG
**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.
string userGmailEmailID = "YourGamilEmailAddress";
string userGmailPasswod = "YourGmailPassword";
Post Photo to Facebook
To post our photo tofacebook we need to a Facebook APPID.To create our APPID go to https://developers.facebook.com/ and login using your facebook id.
After Login to create New App ID enter yourdisplay name and click Create App ID
https://code.msdn.microsoft.com/site/view/file/140947/1/F1.JPG
Now you can see your App ID has been created.You can use this App ID to post your image to Facebook.
https://code.msdn.microsoft.com/site/view/file/140948/1/F2.JPG
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.
https://code.msdn.microsoft.com/site/view/file/140950/1/F4.JPG
Click Settings - > Advanced and set theEmbedded browser OAutho Login to “YES”
https://code.msdn.microsoft.com/site/view/file/140951/1/F5.JPG
**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 .https://github.com/DanBrown180/html5-canvas-post-to-facebook-base64
<INPUT TYPE ="Button" id="btnFB" VALUE=" Send to FB " onClick="sendtoFB()">
function sendtoFB() {
var m = confirm("Are you sure Post in FaceBook ");
if (m) {
$.getScript('//connect.facebook.net/en_US/all.js', function () {
// Load the APP / SDK
FB.init({
appId: '398343823690176', // App ID from the App Dashboard
cookie: true, // set sessions cookies to allow your server to access the session?
xfbml: true, // parse XFBML tags on this page?
frictionlessRequests: true,
oauth: true
});
FB.login(function (response) {
if (response.authResponse) {
window.authToken = response.authResponse.accessToken;
PostImageToFacebook(window.authToken)
} else {
}
}, {
scope: 'publish_actions'
});
});
}
}
**Note :**For appId enter your FB appID which you have created.
Once the photo has been posted we can see our new photo in our Facebook page.
https://i1.code.msdn.s-msft.com/aspnet-web-greeting-card-ad8f0699/image/file/146304/1/9.png
You can download the Source Code from this link Download Source Code