在本教程中,我們將學(xué)習(xí)如何使用 FabricJS 將 Image 對象縮放到給定高度。我們可以通過創(chuàng)建fabric.Image的實(shí)例來創(chuàng)建一個(gè)Image對象。由于它是 FabricJS 的基本元素之一,我們還可以通過應(yīng)用角度、不透明度等屬性輕松自定義它。為了將 Image 對象縮放到給定高度,我們使用 scaleToHeight 方法.
語法
scaleToHeight(value: Number, absolute: Boolean): fabric.Object
登錄后復(fù)制
參數(shù)
value – 此參數(shù)接受一個(gè)Number,它確定 Image 對象的新高度值。
absolute – 此參數(shù)接受一個(gè)布爾值,該值確定是否忽略視口。
Image 對象的默認(rèn)外觀
示例
讓我們看一個(gè)代碼示例,看看不使用 scaleToHeight 方法時(shí)圖像對象的外觀。在這種情況下,我們的圖像對象將不會(huì)在水平或垂直方向上縮放。
<!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>
登錄后復(fù)制
使用自定義值傳遞 scaleToHeight 方法
示例
在此示例中,我們將了解如何為 scaleToHeight 方法分配值將圖像對象縮放到給定高度。由于我們已將值傳遞為 100,因此這將是圖像對象的新高度。
<!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 scaleToHeight method with a custom value</h2>
<p>You can see that the new height of our image object is 100</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 scaleToHeight method
image.scaleToHeight(100, false);
// Add it to the canvas
canvas.add(image);
</script>
</body>
</html>
登錄后復(fù)制
以上就是FabricJS – 如何將圖像對象縮放到給定高度?的詳細(xì)內(nèi)容,更多請關(guān)注www.92cms.cn其它相關(guān)文章!






