问题描述
在我的网页中有一个有一些内容的画布,这个内容是单独呈现的(不使用fabric.js)。
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 .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.
您能帮我一下吗?
推荐答案
使用Jason建议的canvas.toDataURL Maggard:
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);
即使添加fabricjs代码后,红色背景应该仍然存在。你也可以使用canvas.toDataURL()函数作为动态图像的src,如果你想能够移动它/ etc。
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);
这篇关于使用fabric.js修改画布,而不删除现有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!