FabricJS – 检查多边形缓存是否脏以及是否需要渲染器?
我们可以通过创建 fabric.Polygon 的实例来创建一个 Polygon 对象。多边形对象可以用任何由一组连接的直线段组成的封闭形状来表示。由于它是 FabricJS 的基本元素之一,因此我们也可以通过应用角度、不透明度等属性轻松自定义它。
我们可以使用 isCacheDirty 方法检查缓存是否脏以及是否需要渲染器。此方法检查缓存是否脏,从而让 FabricJS 知道画布中的某些内容已更改,需要重新渲染。
语法
isCacheDirty( skipCanvas: Boolean )
参数
skipCanvas (可选) − 此参数接受一个 布尔值,当设置为 true 时,跳过画布检查,因为对象绘制在父画布上。
示例 1:使用 isCacheDirty 方法
让我们来看一个代码示例,以查看使用 isCacheDirty 方法时的日志输出。在这种情况下,多边形对象的原始填充颜色为蓝色。但是,FabricJS 默认情况下会将对象标记为脏并刷新它们在下次渲染时。因此,对象的最终颜色为灰色,并且日志输出为 true。
<!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 isCacheDirty method</h2>
<p>
You can open console from dev tools to see that a true value is returned
</p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// Initiate a polygon object
var polygon = new fabric.Polygon(
[
{ x: 250, y: 180 },
{ x: 150, y: 180 },
{ x: 150, y: 50 },
{ x: 200, y: 10 },
],
{
fill: "blue",
strokeWidth: 3,
stroke: "black",
}
);
// Adding it to the canvas
canvas.add(polygon);
// Applying a different fill colour
polygon.fill = "grey";
// Using isCacheDirty method
console.log("Is cache dirty? : ", polygon.isCacheDirty());
</script>
</body>
</html>
示例 2:将 isCacheDirty 方法与 dirty 属性一起使用
让我们来看一个代码示例,以查看将 isCacheDirty 方法与 dirty 属性结合使用时的日志输出。当 dirty 属性设置为“true”时,它将在下次渲染调用中重新渲染对象的缓存。由于我们已为 dirty 分配了“false”值,因此不会重新渲染对象的缓存,因此 isCacheDirty 方法在控制台中返回 false 值。
<!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 isCacheDirty method along with the dirty property</h2>
<p>You can open console from dev tools to see that a false value is returned </p>
<canvas id="canvas"></canvas>
<script>
// Initiate a canvas instance
var canvas = new fabric.Canvas("canvas");
canvas.setWidth(document.body.scrollWidth);
canvas.setHeight(250);
// Initiate a polygon object
var polygon = new fabric.Polygon(
[
{ x: 250, y: 180 },
{ x: 150, y: 180 },
{ x: 150, y: 50 },
{ x: 200, y: 10 },
],
{
fill: "blue",
strokeWidth: 3,
stroke: "black",
dirty: false,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using isCacheDirty method
console.log("Is cache dirty? : ", polygon.isCacheDirty());
</script>
</body>
</html>
结论
在本教程中,我们使用两个简单的示例演示了如何使用 FabricJS 检查多边形的缓存是否脏以及是否需要渲染器。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP