语法scaletowidth(value: number, absolute: boolean): fabric.object
参数 value - 此参数接受一个number,它确定 image 对象的新宽度值。
absolute - 此参数接受一个布尔值,该值确定是否忽略视口。image 对象的默认外观示例让我们看一个代码示例,看看不使用 scaletowidth 方法时图像对象的外观。在这种情况下,我们的图像对象将不会在水平或垂直方向上缩放。
<!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>
使用自定义值传递 scaletowidth 方法示例在此示例中,我们将看到如何为 scaletowidth 方法分配值将图像对象缩放到给定宽度。由于我们已将值传递为 200,因此这将是图像对象的新宽度。
<!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 scaletowidth method with a custom value</h2> <p>you can see that the new width of our image object is 200</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 scaletowidth method image.scaletowidth(200, false); // add it to the canvas canvas.add(image); </script></body></html>
以上就是fabricjs – 如何将图像对象缩放到给定宽度?的详细内容。