最终不得不将画布转换为图像,然后从 html 中的隐藏图像中添加它。
<img class="test-image" src="" style="display:none;" />
在标记中
var addFilterToCanvas = function (name) {
// remove controls on filter click, have to do it before it creates the image to
// get rid of shape controls
canvas.deactivateAll()
var overlayImageUrl = canvas.toDataURL('png');
$('.test-image').attr('src', overlayImageUrl);
var filterImageUrl = $('.test-image').attr('src');
fabric.Image.fromURL(filterImageUrl, function(img) {
// add filter
switch (name) {
case 'Grayscale':
img.filters.push(new fabric.Image.filters.Grayscale());
break;
case 'Sepia':
img.filters.push(new fabric.Image.filters.Sepia());
break;
case 'Sepia2':
img.filters.push(new fabric.Image.filters.Sepia2());
break;
case 'Invert':
img.filters.push(new fabric.Image.filters.Invert());
break;
}
// apply filters and re-render canvas when done
img.applyFilters(canvas.renderAll.bind(canvas));
// center image
img.top = canvas.getHeight() / 2;
img.left = canvas.getWidth() / 2;
// add image onto canvas
canvas.add(img);
});
// remove controls on after filter applied to get rid of
// new image resize controls
canvas.deactivateAll().renderAll();
}