fabric.js - 从canvas API的ImageData对象创建Image对象

时间:2013-09-14 07:27:40

标签: javascript canvas fabricjs

我想在ImageData对象的fabric.js中创建一个图像对象,我们可以从中获取ImageData:

var imgData=ctx.getImageData(10,10,50,50);
//ctx.putImageData(imgData,10,70);

// something liket that
var image = new fabric.Image.fromImageData (...);

有没有办法从ImageData对象创建图像对象?

1 个答案:

答案 0 :(得分:7)

让我把我的想法放在这里,我不喜欢这种方式,但周围没有其他人 -

var ctx = canvas.getContext('2d');
var data = ctx.getImageData(0, 0, 20, 20);

var c = document.createElement('canvas');

c.setAttribute('id', '_temp_canvas');
c.width = 20;
c.height = 20;

c.getContext('2d').putImageData(data, 0, 0);

fabric.Image.fromURL(c.toDataURL(), function(img) {
    img.left = 50;
    img.top = 50;
    canvas.add(img);
    img.bringToFront();
    c = null;
    $('#_temp_canvas').remove();
    canvas.renderAll();
});