简体   繁体   English

使用fabric.js修改画布而不删除现有内容

[英]Modify a canvas using fabric.js without removing existing content

In my web page there is a canvas with some content and this content is rendered separately (without using fabric.js). 在我的网页中,有一个包含某些内容的画布,并且该内容是单独呈现的(不使用fabric.js)。

What I want to do is add some content on top of the existing content, using fabric.js . 我想要做的是使用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? 您能帮我吗?

Using the canvas.toDataURL() function as suggested by Jason Maggard: 使用Jason Maggard建议的canvas.toDataURL()函数:

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. 即使添加了fabricjs代码,红色背景仍然应该在那里。 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. 如果您希望能够在/ etc周围移动它,也可以将canvas.toDataURL()函数用作动态图像的src。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM