fabric.js 教學 (隨便紀錄)

分享至

範例網址:https://fgophoto12.000webhostapp.com

1.創建一個canvas畫板並加上背圖
//preserveObjectStacking: true - 選中的物件不會置頂
var canvas = new fabric.Canvas('draw',{ backgroundImage: "assets/img/fgo-card.jpg",preserveObjectStacking: true});//創建一個canvas畫板並加上背圖

2.在畫布新增一個圖片
fabric.Image.fromURL('assets/img/patten/hreat1.png', function(img) {
      img.scale(1).set({
        left: 150,
        top: 150,
        angle: 0,
        lockRotation: true,//旋轉控制失效
        type:'st'//可用來替物件命名
      });
    
      canvas.add(img);
  });

3.下載canvas圖片(搭配php)
$('.download').click(function(){
  //取消选择画布上的一个或多个对象
  // canvas.deactivateAll().renderAll();

  var fullQuality = canvas.toDataURL("image/png").replace("image/png","image/octet-stream");
  var type = 'png';//图片导出为 png 格式
  // console.log(fullQuality);

  var saveFile = function(data, filename){//這段一定要放前面
      var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
      save_link.href = data;
      save_link.download = filename;

      var event = document.createEvent('MouseEvents');
      event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
      save_link.dispatchEvent(event);
  };

  // 下载后的文件名
  var filename = 'fgo-photo.' + type;
  // download
  saveFile(fullQuality,filename);



 });

4.上傳圖片,取得base64字串傳送給upload.php產生檔案至資料夾
//↓取得base64字串傳送給upload.php產生檔案至資料夾
  var fullQuality2 = canvas.toDataURL("image/png");
  var base64String = fullQuality2.substr(22); //取得base64字串
  // console.log(base64String)
  $.ajax({
            url: "upload.php",
            type: "POST",
            data:  {data:base64String},
            success: function(data){
                console.log(data);
                var pic_name = data;
            },
            error: function(){
            }
        });

----php------------------------------------------------------------------------------------------
<?php
  // 設定圖檔上傳路徑
  define('UPLOAD_PATH', 'assets/img/pic/');

  // 接收 POST 進來的 base64 DtatURI String
  $img = $_POST['data'];

  //轉檔 & 存檔
  $img = str_replace('data:image/png;base64,', '', $img);
  $img = str_replace(' ', '+', $img);
  $data = base64_decode($img);
  $num = uniqid();
  $file = UPLOAD_PATH . $num . '.png';
  $success = file_put_contents($file, $data);

  //output string
  $output = ($success) ? '<img src="'. $file .'" alt="Canvas Image" />' : '<p>Unable to save the file.</p>';

  echo $file;

?>
----php------------------------------------------------------------------------------------------

5.放大物件
$('.big').click(function(){

 var activeObject = canvas.getActiveObject();
            

        if(!activeObject){//找不到物件時
            $('#alert2').modal('show');
        }else{//有找到物件
            var activeObjectScaleX = canvas.getActiveObject().scaleX,
                activeObjectScaleY = canvas.getActiveObject().scaleY;

            activeObject.scale(activeObjectScaleX+0.05);
            // console.log(activeObject)
            canvas.renderAll();
        }

 });

6.縮小物件
$('.small').click(function(){

 var activeObject = canvas.getActiveObject();

        if(!activeObject){//找不到物件時
            $('#alert2').modal('show');
        }else{//有找到物件
            var activeObjectScaleX = canvas.getActiveObject().scaleX,
                activeObjectScaleY = canvas.getActiveObject().scaleY;

            activeObject.scale(activeObjectScaleX-0.05);
            // console.log(activeObject)

            canvas.renderAll();
        }

 });

7.物件向右旋轉
$('.turn-right').click(function(){

  var activeObject = canvas.getActiveObject();

  if(!activeObject){//找不到物件時
   alert('請點選圖片')
  }else{//有找到物件
   var activeObjectAngle = canvas.getActiveObject().angle,
    activeObjectType = canvas.getActiveObject().type;

   console.log(activeObject)

   if(activeObjectType=="st"){
    alert('從者無法旋轉')
   }else{
    activeObject.rotate(activeObjectAngle+10);
   
    canvas.renderAll();
   }
  }

 });

8.物件向左旋轉
$('.turn-left').click(function(){

  var activeObject = canvas.getActiveObject();

  console.log(activeObject)

  if(!activeObject){//找不到物件時
   alert('請點選圖片')
  }else{//有找到物件
   var activeObjectAngle = canvas.getActiveObject().angle,
    activeObjectType = canvas.getActiveObject().type;

   console.log(activeObject)

   if(activeObjectType=="st"){
    alert('從者無法旋轉')
   }else{
    activeObject.rotate(activeObjectAngle-10);
   
    canvas.renderAll();
   }
  }

 });

9.物件往上一層
$('.bring-forward').click(function() {
        var activeObject=canvas.getActiveObject(),
            activeObjects=canvas.getActiveObjects();
        if (activeObject) {
            canvas.bringForward(activeObject);
            canvas.renderAll();
        }else if (activeObjects) {
   canvas.getActiveGroup().forEachObject(function(o){canvas.bringForward(o); });
   //activeGroup.bringForward();
   canvas.renderAll();
        }

    });

10.物件往下一層
$('.send-backward').click(function() {
        var activeObject=canvas.getActiveObject(),
            activeObjects=canvas.getActiveObjects();
        if (activeObject) {
            canvas.sendBackwards(activeObject);
            canvas.renderAll();
        }else if (activeObjects) {
   canvas.getActiveGroup().forEachObject(function(o){canvas.sendBackwards(o); });
   //activeGroup.sendBackwards();
   canvas.renderAll();
        }
    });

發表迴響