使用 canvas.loadFromJSON(json,function(){
如果图像已应用过滤器,则会出现以下错误。
错误似乎在ln 19484处,我在try catch块中包装并执行console.log('元素绘制' + elementToDraw.toString())和console.log( ' ctx' + ctx.toString())以查看元素是否存在
elementToDraw && ctx.drawImage(elementToDraw,
x + imageMargins.marginX,
y + imageMargins.marginY,
imageMargins.width,
imageMargins.height
);
element to draw[object Image]
ctx[object CanvasRenderingContext2D]
TypeError: Image or Canvas expected
at TypeError (native)
at klass._render (fabric.js:19486:28)
at klass.drawObject (fabric.js:13079:12)
at klass.render (fabric.js:13016:14)
at klass._renderObjects (fabric.js:7091:34)
at klass.renderCanvas (fabric.js:7069:12)
at klass.renderAll (fabric.js:9019:12)
at fabric.js:11619:15
at cbIfLoaded (fabric.js:11646:21)
at klass.__setBgOverlay (fabric.js:11668:19)
json loaded
Fabric对象是客户端生成的,然后上传到Fabric 1.7.22在节点下运行的服务器。我测试了1.5.0,1.6.0和1.7.22,三者都没有显示出差异。
服务器正在运行节点v6.12.3
当我在命令行上运行时:
var fs = require('fs'),
fabric = require('fabric').fabric,
out = fs.createWriteStream(__dirname + '/helloworld.png');
var canvas = fabric.createCanvasForNode(400, 400);
try{
var src = __dirname + '/client_318-CL-Tatnall_4x3_art.png';
fs.readFile(src, function(erro, data) {
if (erro) console.log(erro);
fabric.Image.fromURL(src, function (img) {
img.src = src;
img.filters.push( new fabric.Image.filters.Sepia());
img.filters.push(new fabric.Image.filters.Grayscale());
img.crossOrigin = "anonymous";
img.width = canvas.width;
img.height = canvas.height;
console.log(img);
try{
img.applyFilters();
canvas.add(img)
} catch(err){
console.log(err);
}
var stream = canvas.createPNGStream();
stream.on('data', function(chunk) {
out.write(chunk);
});
return;
}, {crossOrigin: "anonymous"});
return;
});
} catch(err){
console.log(err);
}

我得到了同样的错误
答案 0 :(得分:0)
我找到了这个网站https://www.bountysource.com/issues/6655913-node-canvas-image-or-canvas-expected-on-canvas-add-img:
它解释了这个问题并提供了解决方案:
var Canvas = require('canvas');
var createCanvasForNode = fabric.createCanvasForNode;
fabric.createCanvasForNode = function () {
canvas = createCanvasForNode.apply(this, arguments);
canvas.nodeCanvas = new Canvas(canvas.width, canvas.height);
canvas.contextContainer = canvas.nodeCanvas.getContext('2d');
return canvas;
};

添加此项可修复此问题。