本文主要以实例的形式给大家演示如何用HTML5的Canvas绘图,并将图片保存成文件。
前端代码:
JavaScript代码
- function drawArrow(angle)
- {
-
- var canvas = $('#cv_Arrow')[0];
- var context = canvas.getContext('2d');
- var width = canvas.width;
- var height = canvas.height;
- context.clearRect(0, 0, width, height);
-
-
- 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);
-
-
- context.fillStyle = 'rgb(0,0,0)';
- context.lineWidth = 1;
- context.strokeStyle = "#000000";
- context.lineCap = 'round';
- 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)';
- 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;
- }
发送到后台的代码:
JavaScript代码
- for (var i = 0; i < 360; i++)
- {
- drawArrow(1);
-
- var data = _canvas.toDataURL();
-
-
- var b64 = data.substring(22);
-
- $.ajax({ url: "RotateCanvas.aspx", data: { data: b64, name: i.toString() }, success:
- function ()
- {
-
- }
- });
- }
后台接收的代码:
C#代码
- 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)
- {
- }
- }
最后生成的效果:
生成图片的效果很棒,不失真,而且是透明的,不需要后期处理。