HTML5 canvas画图及图片上传服务器

人民时讯快报 次浏览

上一个教程中我们实现了使用html5 canvas来制作涂鸦画板的效果,在这个教程中,我们将讲解如何将画好的图片上传到服务器上。

最后的效果如下图,当点击“开始画图”按钮,将在canvas画布中绘制渐变的背景色和一些文本,当点击“上传到服务器”按钮时,js脚本将从canvas中提取图片的数据,然后将图片数据上传到指定的服务器上。

html5 canvas画图

HTML结构

我们需要在html页面上创建3个元素:

一个canvas元素,用于绘制图片,实际绘图在js文件中完成。

一个用于触发绘图操作的按钮。

一个用于上传在canvas中绘制好的图片的按钮。

<form runat="server"> <div> <canvas></canvas> <ul> <li><button>开始画图</button></li> <li><button>上传到服务器</button></li> </ul> </div> </form> JAVASCRIPT

在js代码中要完成两项工作:在canvas画布中绘制图像和使用ajax来上传图片。我们写两个函数来分别完成这两项工作。一个hisDrawPic()函数,用于绘图。一个是UploadPic()函数,用于上传图片。

function DrawPic() { // Get the canvas element and its 2d context var Cnv = document.getElementById('myCanvas'); var Cntx = Cnv.getContext('2d'); // Create gradient var Grd = Cntx.createRadialGradient(100, 100, 20, 140, 100, 230); Grd.addColorStop(0, "red"); Grd.addColorStop(1, "black"); // Fill with gradient Cntx.fillStyle = Grd; Cntx.fillRect(0, 0, 300, 200); // Write some text for (i=1; i<10 ; i++) { Cntx.fillStyle = "white"; Cntx.font = "36px Verdana"; Cntx.globalAlpha = (i-1) / 9; Cntx.fillText("Codicode.com", i * 3 , i * 20); } } function UploadPic() { // Generate the image data var Pic = document.getElementById("myCanvas").toDataURL("image/png"); Pic = Pic.replace(/^data:image\/(png|jpg);base64,/, "") // Sending the image data to Server $.ajax({ type: 'POST', url: 'Save_Picture.aspx/UploadPic', data: '{ "imageData" : "' + Pic + '" }', contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (msg) { alert("Done, Picture Uploaded."); } }); } 服务器端代码

在本例子中我们使用 Asp.Net C#来作为服务器端语言,PHP和JAVA版本的代码基本类似,相信你比我更熟悉它们。^_^!!

using System; using System.Web; using System.IO; using System.Web.Script.Services; using System.Web.Services; [ScriptService] public partial class Save_Picture : System.Web.UI.Page { [WebMethod()] public static void UploadPic (string imageData) { string Pic_Path = HttpContext.Current.Server.MapPath("MyPicture.png"); using (FileStream fs = new FileStream(Pic_Path, FileMode.Create)) { using (BinaryWriter bw = new BinaryWriter(fs)) { byte[] data = Convert.FromBase64String(imageData); bw.Write(data); bw.Close(); } } } }

到此一个简单实用html5 canvas画图级上传到服务器的过程就讲解完了,希望你能从中获益!!