如何使用 FabricJS 创建图像对象的字符串表示形式?

在本教程中,我们将向您展示如何创建一个字符串表示形式 使用 FabricJS 的图像对象。我们可以通过创建一个实例来创建一个 Image 对象 织物.图像。由于它是FabricJS的基本元素之一,我们也可以轻松地 通过应用角度、不透明度等属性来自定义它。为了创建一个字符串 Image 对象的表示,我们使用 toString 方法。
语法
toString(): String
使用toString方法
示例
让我们看一个代码示例,看看使用 toString 方法时记录的输出。在 在这种情况下,将返回图像实例的字符串表示形式。
<!DOCTYPE html>
<html>
<head>
<!-- Adding the Fabric JS Library-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script>
</head>
<body>
<h2>Using the toString method</h2>
<p>
You can open console from dev tools and see that the logged output contains the String representation of the image instance
</p>
<canvas id="canvas"></canvas>
<img
src="https://www.tutorialspoint.com/images/logo.png"
id="img1"
style="display: none"
/>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// Initiating the image element
var imageElement = document.getElementById("img1");
// Initiate an Image object
var image = new fabric.Image(imageElement, {
top: 50,
left: 110,
});
// Add it to the canvas
canvas.add(image);
// Using the toString method
console.log(
"String representation of the Image instance is: ",
image.toString()
);
</script>
</body>
</html>
使用toString方法比较两个不同的元素
示例
让我们看一个代码示例,看看如何通过查看两个对象来比较它们 各自的字符串表示。在这里,我们初始化了一个 Image 实例和一个 矩形实例。在对每个对象应用 toString 方法时,我们可以看到它们的 控制台中各自的字符串表示形式。
<!DOCTYPE html>
<html>
<head>
<!-- Adding the Fabric JS Library-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script>
</head>
<body>
<h2>Using toString method to compare two different elements</h2>
<p>
You can open console from dev tools and see that the logged output contains the String representation of the Image instance and the rectangle instance
</p>
<canvas id="canvas"></canvas>
<img src="https://www.tutorialspoint.com/images/logo.png" id="img1" style="display: none" />
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// Initiating the image element
var imageElement = document.getElementById("img1");
// Initiate an Image object
var image = new fabric.Image(imageElement, {
top: 50,
left: 110,
});
// Initiate a Rectangle object
var rect = new fabric.Rect({
stroke: "red",
strokeWidth: 20,
width: 20,
height: 50,
left: 460,
top: 55,
});
// Add them to the canvas
canvas.add(image);
canvas.add(rect);
// Using the toString method
console.log(
"String representation of the Image instance is: ",
image.toString()
);
console.log(
"String representation of the Rectangle instance is: ",
rect.toString()
);
</script>
</body>
</html>
结论
在本教程中,我们使用两个示例来演示如何创建字符串 使用 FabricJS 表示 Image 对象。
javascript