HTML5 canvas 画图保存上传

来源:互联网 发布:编程工具排行榜 编辑:程序博客网 时间:2024/06/16 16:27

如何将画好的图片上传到服务器上。

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

 HTML结构

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

  • 一个canvas元素,用于绘制图片,实际绘图在js文件中完成。
  • 一个用于触发绘图操作的按钮。
  • 一个用于上传在canvas中绘制好的图片的按钮。
<formid="form1"runat="server">
    <divalign="center"class="i-canvas">
        <canvasid="myCanvas"width="500"height="300"></canvas>
        <ul>
            <li><buttononclick="javascript:DrawPic();return false;">开始画图</button></li>
            <li><buttononclick="javascript:UploadPic();return false;">上传到服务器</button></li>
        </ul>
    </div>
</form>                               

 JAVASCRIPT

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

functionDrawPic() {
     
    // Get the canvas element and its 2d context
    varCnv = document.getElementById('myCanvas');
    varCntx = Cnv.getContext('2d');
         
    // Create gradient
    varGrd = 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);
    }
}
     
functionUploadPic() {
     
    // Generate the image data
    varPic = 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();
            }
        }
    }
}                               
0 0
原创粉丝点击