當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Fabric.js Image cropX屬性用法及代碼示例

Fabric.js是一個JavaScript庫,用於處理畫布。 canvas圖像是用於創建圖像實例的fabric.js類之一。畫布圖像表示圖像是可移動的,可以根據需要進行拉伸。圖像的cropX屬性用於裁剪一定數量的畫布圖像。大小以像素為單位。

方法:首先導入fabric.js庫。導入庫後,在body標簽中創建一個畫布塊,其中將包含圖像。之後,初始化Canvas和Fabric.JS提供的圖像類的實例,並使用image對象的cropX屬性給出要裁剪的畫布圖像的寬度(以像素為單位)。

用法:

fabric.Image(image, {
    cropX:Number
});

參數:上麵的函數采用上麵提到的和下麵描述的兩個參數:

  • image:此參數拍攝圖像。
  • cropX:此參數是距圖像原始尺寸的圖像裁剪量(以像素為單位)。

例:本示例使用FabricJS沿x軸裁剪畫布圖像的一部分,如下麵的示例所示。



   
<!DOCTYPE html>  
<html>  
  
<head>  
    <!-- Adding the FabricJS library --> 
    <script src=  
"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js">  
    </script>  
</head>  
  
<body>  
    <h1 style="color:green;">GeeksforGeeks</h1>  
    <b>Fabric.js | Image cropX Property </b>  
  
    <canvas id="canvas" width="400" height="300"
        style="border:2px solid #000000">  
    </canvas>  
  
    <img src = 
"https://media.geeksforgeeks.org/wp-content/uploads/20200327230544/g4gicon.png" 
        width="100" height="100" id="my-image"
        style="display:none;"><br> 
  
    <button onclick="cropX()">Click me</button> 
  
    <script>  
      
        // Create the instance of canvas object 
        var canvas = new fabric.Canvas("canvas");  
  
        // Getting the image 
        var img= document.getElementById('my-image'); 
  
        // Creating the image instance  
        var imgInstance = new fabric.Image(img, { 
        }); 
        function cropX() { 
            imgInstance = new fabric.Image(img, { 
                cropX:80 
            }); 
            canvas.clear(); 
            canvas.add(imgInstance); 
        } 
  
        // Rendering the image to canvas 
        canvas.add(imgInstance); 
    </script>  
</body>  
  
</html>

輸出:

在單擊按鈕之前:

單擊按鈕後:




相關用法


注:本文由純淨天空篩選整理自tarun007大神的英文原創作品 Fabric.js Image cropX Property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。