所以我只是搞乱了针对Node.JS的Fabric.JS ,而不是网络,我设法制作了一个静态画布,并在其上放了一个矩形。出口时间。这是我创建画布和添加矩形的代码:
import c
以下是我尝试导出图片的所有内容:
var canvas = new fabric.StaticCanvas(null, {width: 200, height: 200})
var rect = new fabric.Rect({
left: 100,
top: 100,
width: 100,
height: 50,
fill: "red"
})
canvas.add(rect)
//Creates a PNG file that isn't generated correctly. It's as if it's corrupt. No program can open it
canvas.createPNGStream().on("data", function (chunk) {
fs.createWriteStream(__dirname + "/output.png").write(chunk)
})
//Causes a crash
canvas.createJPEGStream().on("data", function (chunk) {
fs.createWriteStream(__dirname + "/output.jpeg").write(chunk)
})
Error:
C:\Users\me\Documents\my project\node_modules\canvas\lib\jpegstream.js:44
canvas[method](options.bufsize, options.quality, options.progressive, function(err, chunk){
^
TypeError: canvas[method] is not a function
at C:\Users\me\Documents\my project\node_modules\canvas\lib\jpegstream.js:44:19
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
//Same thing as first try^^, except it's a JPEG
canvas.createJPEGStream({quality: 100}).pipe(fs.createWriteStream(__dirname + "/output.jpeg"))
注意://This one makes the PNG file, but when it's opened, its 100% transparent. That's it. The rectangle I added isn't there. Canvas size is correct, however
canvas.createPNGStream().pipe(fs.createWriteStream(__dirname + "/output.png"))
似乎与fabric.Canvas(null, {width: 200, height: 200})
完全相同,在这种情况下
注2:此代码:
StaticCanvas
导致此错误:
var canvas = new fabric.createCanvasForNode(200, 200)
这里有什么我想念的吗?这些方法似乎都没有起作用,而且这些都是我在谷歌上找到的。导出图像的正确方法是什么?它可以是PNG或JPEG / JPG,最好是PNG,但JPEG / JPG可以。任何常见的格式。
答案 0 :(得分:2)
找到答案。 canvas.createPNGStream().pipe(fs.createWriteStream(__dirname + "/output.png"))
确实有效。它完全是空的原因是因为看起来canvas.add()
不是一个瞬间的行动。在输出文件之前,我所做的只是setTimeout()
。希望这有助于某人!
答案 1 :(得分:0)
我使用了node-canvas
中的示例代码,它可以正常工作
const fs = require('fs')
const out = fs.createWriteStream(__dirname + '/test.png')
const stream = canvas.createPNGStream()
stream.pipe(out)
out.on('finish', () => console.log('The PNG file was created.'))