canvas.toDataURL()用于大画布 [英] canvas.toDataURL() for large canvas

查看:267
本文介绍了canvas.toDataURL()用于大画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于大画布,我有一个 .toDataURL()的问题。我想在 base64 中解析并解码php文件,但如果我有一个大画布, strDataURI 变量是空的。



我的代码:

  var strDataURI = canvas.toDataURL ; 
strDataURI = strDataURI.substr(22,strDataURI.length);
$ .post(save.php,
{
str:strDataURI
};

.toDataURL()还有其他方法可以改变大小限制吗?



谢谢。

解决方案

我不确定是否有画布尺寸的限制,根据浏览器而有所限制:数据网址大小限制



你可以尝试使用Node.js + node-canvas(服务器端)重新创建canvas。我一直使用这些来从canvas元素创建可打印的图像,到目前为止,使用toDataURL的任何问题/限制。



你使用fabric.js库吗?我注意到你发布在他们的论坛上
Fabric.js可以在Node.js中使用,并且拥有 toDataURLWithMultiplier 方法,它缩放画布/上下文,允许您更改dataurl图像大小。



编辑:



由于您使用fabric.js我建议使用Node.js来处理画布到服务器上的图像处理。您可以在此处找到有关如何在Node.js上使用fabric.js的详细信息。 p>

这里是一个使用Node.js和express的简单服务器:

  var express = require('express'),
fs = require('fs'),
fabric = require('fabric')fabric,
app = express b端口= 3000;

var allowCrossDomain = function(req,res,next){
res.header('Access-Control-Allow-Origin','*');
res.header('Access-Control-Allow-Methods','POST,OPTIONS');
res.header('Access-Control-Allow-Headers','Content-Type');
next();
}

app.configure(function(){
app.use(express.bodyParser());
app.use(allowCrossDomain);
});

app.options('/',function(req,res){
res.send(200);
});

app.post('/',function(req,res){
var canvas = fabric.createCanvasForNode(req.body.width,req.body.height);

console.log('> Loading JSON ...');
canvas.loadFromJSON(req.body.json,function(){
canvas.renderAll();

console.log('>获取PNG数据...(这可能需要一段时间)');
var dataUrl = canvas.toDataURLWithMultiplier('png',req.bodyMultiplier) ,
data = dataUrl.replace(/ ^ data:image\ / png; base64,/,'');

console.log('>将PNG保存到文件.. 。');
var filePath = __dirname +'/test.png';
fs.writeFile(filePath,data,'base64',function(err){
if
console.log('!保存PNG时出错:'+ err);
res.json(200,{error:'Error saving PNG:'+ err});
} else {
console.log('> PNG file saved to:'+ filePath);
res.json(200,{success:'PNG file saved to:'+ filePath}
}
});
});
});

app.listen(port);
console.log('>服务器侦听端口'+端口);

当服务器运行时,您可以向它发送数据( postData )。
服务器期望 json width height 重新创建画布,并使用乘法器缩放数据网址图像。客户端代码看起来像这样:

  var postData = {
json:canvas.toJSON
width:canvas.getWidth(),
height:canvas.getHeight(),
multiplier:2
};

$ .ajax({
url:'http:// localhost:3000',
type:'POST',
contentType:'application / json; charset = utf-8',
data:JSON.stringify(postData),
dataType:'json',
success:function(data){
console.log );
},
错误:function(err){
console.log(err);
}
});


I have a problem with .toDataURL() for large canvas. I want to enconde in base64 and decode on php file but if I have a large canvas the strDataURI variable is empty.

My code:

var strDataURI = canvas.toDataURL();
strDataURI = strDataURI.substr(22, strDataURI.length);
$.post("save.php",
{ 
   str: strDataURI
};

Is there any alternative to .toDataURL() or some way to change the size limit?

Thanks.

解决方案

I'm not sure if there are limitation to canvas dimensions, but data urls have limitations depending on the browser: Data URL size limitations.

What you could try is using Node.js + node-canvas (server side) to recreate the canvas. I've been using these for creating printable images from canvas elements, and didn't have any problems/limitations using toDataURL so far.

Are you using the fabric.js library? I noticed you posted on their forum as well. Fabric.js can be used in Node.js and has a toDataURLWithMultiplier method, which scales the canvas/context allowing you to change the dataurl image size. You can check the method source to see how this is done.

Edit:

Since you're using fabric.js I would suggest using Node.js to handle the canvas to image processing on the server. You'll find more info on how to use fabric.js on Node.js here.

Here is a simple server using Node.js and express:

var express = require('express'),
    fs = require('fs'),
    fabric = require('fabric').fabric,
    app = express(),
    port = 3000;

var allowCrossDomain = function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'POST, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
}

app.configure(function() {
    app.use(express.bodyParser());
    app.use(allowCrossDomain);
});

app.options('/', function(req, res) {
    res.send(200);
});

app.post('/', function(req, res) {
    var canvas = fabric.createCanvasForNode(req.body.width, req.body.height);

    console.log('> Loading JSON ...');
    canvas.loadFromJSON(req.body.json, function() {
        canvas.renderAll();

        console.log('> Getting PNG data ... (this can take a while)');
        var dataUrl = canvas.toDataURLWithMultiplier('png', req.body.multiplier),
            data = dataUrl.replace(/^data:image\/png;base64,/, '');

        console.log('> Saving PNG to file ...');
        var filePath = __dirname + '/test.png';
        fs.writeFile(filePath, data, 'base64', function(err) {
            if (err) {
                console.log('! Error saving PNG: ' + err);
                res.json(200, { error: 'Error saving PNG: ' + err });
            } else {
                console.log('> PNG file saved to: ' + filePath);
                res.json(200, { success: 'PNG file saved to: ' + filePath });
            }
        });
    });
});

app.listen(port);
console.log('> Server listening on port ' + port);

When the server is running you can send data to it (postData). The server expects json, width and height to recreate the canvas, and a multiplier to scale the data url image. The client side code would look something like this:

var postData = {
    json: canvas.toJSON(),
    width: canvas.getWidth(),
    height: canvas.getHeight(),
    multiplier: 2
};

$.ajax({
    url: 'http://localhost:3000',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(postData),
    dataType: 'json',
    success: function(data) {
        console.log(data);
    },
    error: function(err) {
        console.log(err);
    }
});

这篇关于canvas.toDataURL()用于大画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆