在本教程中,我们将学习如何使用 fabricjs 在水平和垂直方向上均匀缩放图像。我们可以通过创建fabric.image的实例来创建一个image对象。由于它是 fabricjs 的基本元素之一,我们还可以通过应用角度、不透明度等属性轻松自定义它。为了在水平和垂直方向上均匀缩放图像,我们使用 scale方法。
语法scale(value: number): fabric.object
参数 scale - 此参数接受一个number,用于设置图像对象的比例因子。
image 对象的默认外观示例让我们看一个代码示例,看看我们的图像对象在不使用scale方法时的样子。在这种情况下,我们的图像对象将不会在水平和垂直方向上缩放。
<!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 that the object has not been scaled in horizontal or vertical direction </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>
使用自定义值传递 scale 方法示例在这个例子中,我们现在将看到正在为scale方法分配一个值,该方法在水平和垂直方向上同等地缩放我们的图像对象。由于我们已将值传递为 2,因此这就是现在要考虑的比例因子。
<!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>passing the scale method with a custom value</h2> <p> you can see that the object has been scaled in horizontal and vertical direction </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, }); // using the scale method image.scale(2); // add it to the canvas canvas.add(image); </script></body></html>
以上就是fabricjs – 如何在水平和垂直方向上均匀缩放图像?的详细内容。