Introduction
In my previous article, ASP.NET Web Photo Editing Tool Using HTML 5, I explained 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:
- 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. I have downloaded all the free images from the Icon Finder.
- 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, “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. Also, send the card to a user entered email address.
- Post Canvas Greeting Card to Facebook: The Final Edited Greeting Card can be posted to Facebook.
Prerequisites
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:
<canvas id="canvas" width="400" height="400"></canvas>
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 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:
<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>
var canvas;
var ctx;
var canvasEffect;
var ctxEffect;
var x = 75;
var y = 50;
var WIDTH = 200;
var HEIGHT = 252;
var Colors = "";
var newPaint = false;
var DrawingTypes = "";
var radius = 30;
var radius_New = 30;
var stickerWidth = 40, stickerHeight = 40;
rect = {},
drag = false;
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();
var prevX = 0,
currX = 0,
prevY = 0,
currY = 0;
var ImageNames = new Array();
var imageCount = 0;
var imageObj = new Image();
var imageObj_BG = new Image();
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.
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
:
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.
<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
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.
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";
break;
case "Images":
imageObj.src = ImageNames[imageCount - 1];
ctx.drawImage(imageObj, rect.startX, rect.startY, rect.w, rect.h);
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();
}
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.
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 to Facebook, we need to have 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 your Display 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. Take a look at this reference link which explains how to convert and embed HTML5 Canvas 5 Image to base64
.
function sendtoFB() {
var m = confirm("Are you sure Post in FaceBook ");
if (m) {
$.getScript('//connect.facebook.net/en_US/all.js', function () {
FB.init({
appId: 'YOURFBAPPID',
cookie: true,
xfbml: true,
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.
Points of Interest
Note: If your posted Photo on Facebook is not visible to other users, then you have to set your app to live. To make your app live, go to your App Facebook page, select Settings and set "Do you want to make this app and all its live features available to the general public?"to YES.
Tested Browsers
- Chrome
- Internet Explorer 10
History
- 21st December, 2015: Initial version