I have a Fabric.js canvas with a background image that has some transparent parts. I want the transparent parts to show the color of the div behind the canvas (e.g. red). So this works:
canvas.setBackgroundColor(null);
canvas.setBackgroundImage(image, canvas.renderAll.bind(canvas), {
opacity: 1.0
});
Now say I want to to change the opacity of the image to 0.3. In this case the non-transparent parts of the image show the red underneath. But I would like the transparent parts to show red, and the non-transparent parts to be faded against a white background. Is this possible?
答案 0 :(得分:1)
我不确定我是否正确理解你,但你可以加载一个透明的.png,它会在透明部分显示画布背景。
例如:
var canvas = new fabric.Canvas('fabric');
canvas.backgroundColor = 'green';
canvas.renderAll();
fabric.Image.fromURL("https://i.imgur.com/aSEcfuz.png", function(img){
img.left = 0;
img.top = 0;
img.width = 200;
img.height = 200;
canvas.add(img);
});

<canvas id="fabric" width="500" height="500"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.2/fabric.min.js"></script>
&#13;
在图像后面放置白色背景并将其与图像一起移动的解决方法:
var canvas = new fabric.Canvas('fabric');
canvas.backgroundColor = 'green';
canvas.renderAll();
var sharedProperties = {
left: 0,
top: 0,
width: 200,
height: 200
};
var image;
var rect = new fabric.Rect({
left: sharedProperties.left,
top: sharedProperties.top,
fill: 'white',
width: sharedProperties.width,
height: sharedProperties.height
});
canvas.add(rect);
fabric.Image.fromURL("https://i.imgur.com/aSEcfuz.png", function(img) {
image = img;
img.left = sharedProperties.left;
img.top = sharedProperties.top;
img.width = sharedProperties.width;
img.height = sharedProperties.height;
canvas.add(img);
image.on('moving', function(event) {
rect.set({
left: image.left,
top: image.top
});
rect.setCoords();
});
});
&#13;
<canvas id="fabric" width="500" height="500"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.2/fabric.min.js"></script>
&#13;