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

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 16:47   1280   0

前端的代码:

[javascript]

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;

}

发送到后台的代码:

[javascript]

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');

}

});

}

后台接收的代码:

[csharp]

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)

{

}

}

最后生成的结果:

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

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP