在本教程中,我们将学习如何将图像对象水平居中使用 fabricjs 的画布的当前视口。我们可以通过创建一个 image 对象fabric.image 的实例。由于它是fabricjs的基本元素之一,我们可以还可以通过应用角度、不透明度等属性轻松自定义它。水平放置在画布当前视口上的 image 对象,我们使用 viewportcenterh方法。
语法viewportcenterh(): fabric.object
image 对象的默认外观示例让我们看一个代码示例,看看当 viewportcenterh方法没有被使用。在这种情况下,图像对象将不会水平居中画布。
<!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>default appearance of the image object</h2> <p>you can see the default appearance of image object</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); </script></body></html>
使用viewportcenterh方法示例让我们看一个代码示例,看看图像对象在使用viewportcenterh方法。在这种情况下,我们的图像对象将居中horizontally with respect to the current viewport of 画布。
<!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 viewportcenterh method</h2> <p> you can see that the image object is centered horizontally with respect to the current viewport of canvas </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 viewportcenterh method image.viewportcenterh(); </script></body></html>
结论在本教程中,我们使用两个示例来演示如何使图像对象居中使用 fabricjs 在画布的当前视口上水平放置。
以上就是如何使用 fabricjs 将 image 对象在画布的当前视口中水平居中?的详细内容。