ControlAboveOverlay — это свойство в Fabric.js. Это логическое значение, которое, если ему присвоено значение true, отображает элементы управления (границы, углы и т. д.) объекта над наложенным изображением. Наложенное изображение — это изображение, которое можно настроить для отображения поверх холста.
В настоящее время он дает следующий результат. Внешняя часть имеет только элементы управления.
Я хотел бы показать внешнюю часть элемента с непрозрачностью 0,5. Как показано ниже.
Вот пример HTML-кода.
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8" />
<meta name = "viewport" content = "width=device-width, initial-scale=1.0" />
<title>Fabric.js Example with controlsAboveOverlay</title>
<!-- Importing the Fabric.js library -->
<script src = "https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.3.1/fabric.min.js"></script>
</head>
<body>
<!-- Creating a canvas element with id 'canvas' -->
<canvas id = "canvas" width = "400" height = "400"></canvas>
<style>
.canvas-container {
/* Setting the background color of the canvas container */
background-color: #f0f0f0;
}
</style>
<script>
(function () {
/* Initializing a new Fabric.js canvas with certain properties */
var canvas = new fabric.Canvas("canvas", {
width: 600,
height: 500,
backgroundColor: "#ffffff",
/* Setting controlsAboveOverlay to true to render controls above the overlay image */
controlsAboveOverlay: true,
});
/* Creating a rectangular clip path */
var clipPath = new fabric.Rect({
width: 300,
height: 300,
left: (canvas.getWidth() - 300) / 2,
top: 10,
});
/* Creating a group of objects, in this case, a single rectangle */
var group = new fabric.Group([
new fabric.Rect({
width: 100,
height: 100,
fill: "red",
left: (canvas.getWidth() - 150) / 2,
top: 10,
}),
]);
/* Applying the clip path to the canvas */
canvas.clipPath = clipPath;
/* Adding the group of objects to the canvas */
canvas.add(group);
})();
</script>
</body>
</html>
Нарисуйте путь с обтравочной маской SVG.
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8" />
<meta name = "viewport" content = "width=device-width, initial-scale=1.0" />
<title>Fabric.js Example with controlsAboveOverlay</title>
<!-- Importing the Fabric.js library -->
<script src = "https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.3.1/fabric.min.js"></script>
</head>
<body>
<!-- Creating a canvas element with id 'canvas' -->
<canvas id = "canvas" width = "400" height = "400"></canvas>
<style>
.canvas-container {
/* Setting the background color of the canvas container */
background-color: #f0f0f0;
}
</style>
<script>
(function () {
/* Initializing a new Fabric.js canvas with certain properties */
var canvas = new fabric.Canvas("canvas", {
width: 600,
height: 600,
backgroundColor: "#ffffff",
/* Setting preserveOjectStacking to prevent othe object to stack over the overlay */
preserveObjectStacking: true,
});
var top = 150; // origin of the inner clipping rectangle y
var left = 150; // origin of the inner clipping rectangle x
var canvasPadding = 2000; // padding for the canvas
var paddingHalf = canvasPadding / 2; // half of the padding
var viewWidth = 300; // width of the inner clipping rectangle
var viewHeight = 300; // height of the inner clipping rectangle
/* Creating a SVG mask for the canvas */
var maskPath = `M 0 0 L ${canvasPadding} 0 L ${canvasPadding} ${canvasPadding} L 0 ${canvasPadding} L0 0 Z
M ${paddingHalf + top} ${paddingHalf + top}
L ${paddingHalf + left} ${paddingHalf + top + viewHeight}
L ${paddingHalf + left + viewWidth} ${paddingHalf + top + viewHeight}
L ${paddingHalf + left + viewWidth} ${paddingHalf + top}
L ${paddingHalf + left} ${paddingHalf + top} Z
`;
var mask = new fabric.Path(maskPath, {
fill: "rgba(0, 0, 0)",
opacity: 0.5,
left: -paddingHalf,
top: -paddingHalf,
selectable: false,
evented: false,
});
/* Creating a group of objects, in this case, a single rectangle */
var group = new fabric.Group([
new fabric.Rect({
top: 0,
left: 0,
width: 100,
height: 100,
fill: "red",
left: (canvas.getWidth() - 150) / 2,
top: 10,
}),
]);
/* Adding the group of objects to the canvas */
canvas.add(group);
canvas.add(mask);
})();
</script>
</body>
</html>
Мы можем добиться аналогичного эффекта, используя два перекрывающихся объекта:
По сути, когда мы добавляем какой-либо объект, мы создаем его дубликат с полупрозрачным эффектом. поэтому у нас будет два объекта для каждого эффекта. 1) оригинал 2) дубликат с эффектом полупрозрачности.
Идея состоит в том, что когда изображение перемещается за пределы холста, исходное изображение будет обрезано, а дубликат (полупрозрачный) будет отображаться снаружи. Для этого мы обновим положение дублированного (полупрозрачного) изображения при перемещении исходного изображения.
Вот пример HTML-кода.
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8" />
<meta name = "viewport" content = "width=device-width, initial-scale=1.0" />
<title>Blur/Opacity Effect of Fabric.js Example</title>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.3.1/fabric.min.js"></script>
</head>
<body>
<canvas id = "canvas" width = "1200" height = "500"></canvas>
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
<script>
(function () {
var canvas = new fabric.Canvas("canvas", {
backgroundColor: "#f0f0f0",
controlsAboveOverlay: true,
selection: false, // Disable group selection
});
// Create a larger square (800x800) at the center of the canvas
var largeSquare = new fabric.Rect({
width: 800,
height: 800,
fill: "#ffffff", // Green color
left: (canvas.getWidth() - 800) / 2,
top: (canvas.getHeight() - 800) / 2,
selectable: false,
absolutePositioned: true,
});
// Create an array of smaller squares as movable objects
var movableSquares = [
// Initial squares...
new fabric.Rect({
width: 200,
height: 200,
fill: "red",
left: (canvas.getWidth() - 200) / 2,
top: (canvas.getHeight() - 200) / 2,
opacity: 1, // Initial opacity
hasControls: true,
lockMovementX: false,
lockMovementY: false,
}),
];
// Create an array of duplicates of the movable squares with opacity 0.5
var movableSquareDups = movableSquares.map(function (square) {
var dup = fabric.util.object.clone(square);
dup.set({ opacity: 0.5 });
return dup;
});
// Apply the clipPath to the original squares
movableSquares.forEach(function (square) {
square.clipPath = largeSquare;
});
// Add the larger square to the canvas
canvas.add(largeSquare);
// Add the duplicate squares to the canvas first, so they're behind the original squares
movableSquareDups.forEach(function (square) {
canvas.add(square);
});
// Add the smaller movable squares to the canvas
movableSquares.forEach(function (square) {
canvas.add(square);
});
var customEvtHandler = function (e) {
var obj = e.target; // The object that's being moved or resized
// Check if the object is one of the movable squares
var index = movableSquares.indexOf(obj);
if (index !== -1) {
// Move and resize the corresponding duplicate square together with the original square
movableSquareDups[index].set({
left: obj.left,
top: obj.top,
scaleX: obj.scaleX,
scaleY: obj.scaleY,
angle: obj.angle,
flipX: obj.flipX,
flipY: obj.flipY,
});
// Update the canvas display
canvas.renderAll();
}
};
// Add event listeners for moving, modifying, scaling, and rotating objects
canvas.on("object:moving", customEvtHandler);
canvas.on("object:modified", customEvtHandler);
canvas.on("object:scaling", customEvtHandler);
canvas.on("object:rotating", customEvtHandler);
})();
</script>
</body>
</html>
Нашел этот материал ссылка
Я уверен, что вы сможете адаптировать это к своему изображению.
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8" />
<meta name = "viewport" content = "width=device-width, initial-scale=1.0" />
<title>Blur/Opacity Effect of Fabric.js Example</title>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.3.1/fabric.min.js"></script>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
z-index: 2;
}
#square {
position: absolute;
width: 200px;
height: 200px;
background-color: red;
opacity: 0.5;
z-index: 1;
}
</style>
</head>
<body>
<div id = "square"></div>
<canvas id = "canvas" width = "1200" height = "500"></canvas>
<script>
(function () {
var canvas = new fabric.Canvas("canvas", {
backgroundColor: "#f0f0f0",
controlsAboveOverlay: true,
selection: false, // Disable group selection
});
// Create a square at the center of the canvas
var redSquare = new fabric.Rect({
width: 200,
height: 200,
fill: "red",
left: (canvas.getWidth() - 200) / 2,
top: (canvas.getHeight() + 200) / 2,
opacity: 1, // Initial opacity
hasControls: true,
lockMovementX: false,
lockMovementY: false,
originX: "left",
originY: "top",
});
var square = document.getElementById("square");``
square.onclick = function() {
canvas.setActiveObject(redSquare);
canvas.renderAll();
};
function positionSquare(obj) {
var absCoords = canvas.getAbsoluteCoords(obj);
square.style.left = absCoords.left + 'px';
square.style.top = absCoords.top + 'px';
}
// Correct implementation of getAbsoluteCoords
fabric.Canvas.prototype.getAbsoluteCoords = function(object) {
var canvasOffset = this._offset || { left: 0, top: 0 };
return {
left: object.left + canvasOffset.left,
top: object.top + canvasOffset.top
};
};
// Position the HTML square initially
positionSquare(redSquare);
// Update the position of the HTML square on move and scale
redSquare.on('moving', function() {
positionSquare(redSquare);
});
redSquare.on('scaling', function() {
positionSquare(redSquare);
});
canvas.add(redSquare);
canvas.renderAll();
})();
</script>
</body>
</html>
Мы хотим показать полупрозрачной только внешнюю часть изображения, а не все изображение.