用html5的canvas生成图片并保存到本地

jopen 12年前

前端的代码:

    function drawArrow(angle)        {            //Init canvas            var canvas = $('#cv_Arrow')[0];            var context = canvas.getContext('2d');            var width = canvas.width;            var height = canvas.height;            context.clearRect(0, 0, width, height);                    //Rotate            var distance = iconSize / 2 * Math.sqrt(2) * Math.sin(angle * Math.PI / 180 / 2) * 2;            var degree = 180 - 45 - (180 - angle) / 2;            var x = distance * Math.sin(degree * Math.PI / 180);            var y = distance * Math.cos(degree * Math.PI / 180);            context.translate(x, -y);            var angleInRadians = angle * Math.PI / 180;            context.rotate(angleInRadians);                    //Draw arrow            context.fillStyle = 'rgb(0,0,0)'; //Black            context.lineWidth = 1;            context.strokeStyle = "#000000"; //Black            context.lineCap = 'round'; //Circle angle            context.lineJoin = 'round';            context.beginPath();            context.moveTo(iconSize / 2, border);            context.lineTo(border, iconSize - border);            context.lineTo(iconSize / 2, iconSize / 2);            context.fill();            context.stroke();            context.closePath();            context.save();                    context.restore();            context.fillStyle = 'rgb(255,255,255)'; //White            context.lineWidth = 1;            context.strokeStyle = "#000000";            context.lineCap = 'round';            context.lineJoin = 'round';            context.beginPath();            context.moveTo(iconSize / 2, border);            context.lineTo(iconSize - border, iconSize - border);            context.lineTo(iconSize / 2, iconSize / 2);            context.fill();            context.stroke();            context.closePath();            context.save();                    _canvas = canvas;        }  
发送到后台的代码:
for (var i = 0; i < 360; i++)  {   drawArrow(1);     var data = _canvas.toDataURL();     //删除字符串前的提示信息 "data:image/png;base64,"   var b64 = data.substring(22);     $.ajax({ url: "RotateCanvas.aspx", data: { data: b64, name: i.toString() }, success:     function ()     {      //alert('OK');     }   });  }
后台接收的代码:
if (Request["name"] != null)  {   string name = Request["name"];   String savePath = Server.MapPath("~/images/output/");     try   {    FileStream fs = File.Create(savePath + "/" + name + ".png");    byte[] bytes = Convert.FromBase64String(Request["data"]);      fs.Write(bytes, 0, bytes.Length);    fs.Close();   }   catch (Exception ex)   {   }  }

最后生成的结果:

 用html5的canvas生成图片并保存到本地

生成图片的效果很棒,不失真,而且透明的,不需要后期处理。

来自:http://blog.csdn.net/jcx5083761/article/details/7991558