Modify a canvas using fabric.js without removing existing content

瘦欲@ 提交于 2019-12-24 11:19:18

问题


In my web page there is a canvas with some content and this content is rendered separately (without using fabric.js).

What I want to do is add some content on top of the existing content, using fabric.js . I tried to do that as follow (sample code),

var canvas = new fabric.Canvas('c');
var path = new fabric.Path('M 0 0 L 200 100 L 170 200 z');
path.set({ left: 120, top: 120 });
canvas.add(path);

But it will remove the existing content from the canvas.

Could you please help me on this?


回答1:


Using the canvas.toDataURL() function as suggested by Jason Maggard:

var c = document.getElementById('c');
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,c.width,c.height);

var bg = c.toDataURL("image/png");

var canvas = new fabric.Canvas('c');
canvas.setBackgroundImage(bg,canvas.renderAll.bind(canvas));
var path = new fabric.Path('M 0 0 L 200 100 L 170 200 z');
path.set({ left: 120, top: 120 });
canvas.add(path);

The red background should still be there even after you add the fabricjs code. You could also use the canvas.toDataURL() function as the src of a dynamic image, if you want to be able to move it around/etc.

var c = document.getElementById('c');
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,c.width,c.height);

var img = new Image();
img.src = c.toDataURL("image/png");

var canvas = new fabric.Canvas('c');
var oldCanvas = new fabric.Image(img,{ width: c.width, height: c.height });

var path = new fabric.Path('M 0 0 L 200 100 L 170 200 z');
path.set({ left: 120, top: 120 });

canvas.add(oldCanvas);
canvas.add(path);


来源:https://stackoverflow.com/questions/28063173/modify-a-canvas-using-fabric-js-without-removing-existing-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!