问题描述
我在HTML 5画布上绘制了一个带有贝塞尔曲线的渐变图像,如下所示:
I've drawn a gradient image with a Bezier Curve on a HTML 5 Canvas like this:
var canvas = $('#canvas1')[0];
if (canvas.getContext) {
var context = canvas.getContext('2d');
var gradient = context.createLinearGradient(0, 0, 0, 100);
gradient.addColorStop(0, 'rgba(193,193,193,1)');
gradient.addColorStop(.20, 'rgba(160,160,160,1)');
gradient.addColorStop(.5, 'rgba(102,102,102,1)');
gradient.addColorStop(.7, 'rgba(91,91,91,1)');
gradient.addColorStop(.97, 'rgba(160,160,160,1)');
gradient.addColorStop(1, 'rgba(193,193,193,1)');
context.fillStyle = gradient;
context.fillRect(0, 0, 500, 100);
var gradient1 = context.createLinearGradient(0, 0, 0, 100);
gradient1.addColorStop(0, '#a1a1a1');
gradient1.addColorStop(.5, '#717171');
gradient1.addColorStop(1, '#a1a1a1');
context.beginPath();
context.moveTo(0, 0);
context.bezierCurveTo(0, 0, 20, 50, 0, 100);
context.lineWidth = 1;
//context.strokeStyle = 'black'; // line color
//context.stroke();
context.fillStyle = gradient1;
context.fill();
context.closePath();
}
现在我想把这张图片保存在硬盘上,请求:
Now I want to save this image on HDD, for this I have formed this request:
var canvas = $('#canvas1')[0];
if (canvas.getContext) {
var context = canvas.getContext('2d');
$.ajax({
url: '/Html5/Export',
type: 'POST',
data: 'img=' + escape(canvas.toDataURL("image/png")),
success: function (data) {
alert('data exported');
}
});
}
在这个服务器端,我写了这个代码(ASP.NET C# ):
On this server side, I've written this code (ASP.NET C#):
[HttpPost]
public ActionResult Export()
{
string img = Request.Params["img"];
ConvertThis(img);
return Content("true");
}
public void ConvertThis(string ImageText)
{
if (ImageText.Length > 0)
{
ImageText = ImageText.Substring(ImageText.IndexOf(",") + 1);
Byte[] bitmapData;
bitmapData = Convert.FromBase64String(ImageText);
System.IO.File.WriteAllBytes(@"c:\logs\random.png", bitmapData);
}
}
但是在服务器端生成的图像完全不同从在Html5 Canvas上绘制的图片。
But the image generated on the server side is totally different from the image drawn on the Html5 Canvas .
我在这里做错了。
推荐答案
canvas.toDataURL("image/png")
返回一个带有数据uri前缀的base64编码字符串,编码两次。从canvas.toDataURL返回的字符串将如下所示:
returns a base64 encoded string with a data uri prefix, so it looks like you are encoding it twice. The string returned from 'canvas.toDataURL' will look something like this:
如果您只对base64编码图像感兴趣,请像这样提取:
If you are interested in only the base64 encoded image, extract it like this:
var base64Image = canvas.toDataURL("image/png");
...
data: 'img=' + base64Image.substr(base64Image.indexOf(',')),
这篇关于无法从Html 5画布生成png图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!