如何在数据库中保存fabric.js旋转坐标并以相同的角度显示结果?

问题描述 投票:0回答:1

如何将旋转的图像和文本坐标保存到数据库并以相同的角度打印图像?我正在尝试将图像保存为文本并显示在结果图像中。

    <!-- jQuery 2.2.3 -->
<script src="plugins/jQuery/jquery-2.2.3.min.js"></script>
<script src="plugins/fabricjs/fabric.min.js"></script>
<!-- Fabric Script new -->
<script>
var canvas = new fabric.Canvas('can');
canvas.on({
    'object:scaling': function(p){
      if (p.target.scaleX < 1)
        p.target._objects[1].scaleX = 1 + (1 -p.target.scaleX )
      else
        p.target._objects[1].scaleX = 1 / (p.target.scaleX)
      if (p.target.scaleY < 1)
        p.target._objects[1].scaleY = 1 + (1 -p.target.scaleY)
      else
        p.target._objects[1].scaleY = 1 / (p.target.scaleY)

      canvas.renderAll()
    },
  });

//canvas.add(profilepic);
var photoCan = new Array(12);
for(var j=0 ; j<12 ; j++) {
  photoCan[j] = photoGroup("User "+ (j+1));
}
var textCan = new Array(12);
for(var j=0 ; j<12 ; j++) {
  textCan[j] = textGroup("Textbox "+ (j+1));
}
function photoGroup (text,x,y,w,h) {
  w = w || 200; //defaults
  h = h || 200;
  x = x || 150;
  y = y || 100;

  var profilepic = new fabric.Rect({
    originX: 'center',
    originY: 'center',
    fill: "#000",
    strokeDashArray: [5, 5],
    stroke: '#fff',
    width: w,
    height: h
  });
  var text = new fabric.Text(text, {
    fontSize: 30,
    fill: "#fff",
    originX: 'center',
    originY: 'center',
  });
  var group = new fabric.Group([ profilepic, text ], {
    left: x,
    top: y,
    angle: 0
  });
  group.lockRotation = false;
  group.lockUniScaling = false;
  return group;
}

function textGroup (text,x,y,w,h) {
  w = w || 300; //defaults
  h = h || 200;
  x = x || 150;
  y = y || 100;
  var profilepic = new fabric.Rect({
    originX: 'center',
    originY: 'center',
    fill: "#2e2e2e",
    strokeDashArray: [5, 5],
    stroke: '#fff',
    width: w,
    height: h,
  });
  var text = new fabric.Text(text, {
    fontSize: 30,
    fill: "#fff",
    originX: 'center',
    originY: 'center',
  });
  var group1 = new fabric.Group([ profilepic, text ], {
    left: x,
    top: y,
    angle: 0,
    lockUniScaling: false,
  });
  group1.lockRotation = false;
  group1.lockUniScaling= false;

  return group1;
}
</script>
<!-- new script -->
<script>
$('document').ready(function() {
  //hide add more buttons
  $(".addButtons").hide();
  $(".removeButtons").hide();
  $("#myDropzonef").hide(); 
  //**********************************Important: Show addButtons if already number is specified***********
  //vars to get num of elements
  var photonum = 0;
  var textnum = 0;
  //vars to get MAX
  var phototot = 12;
  var texttot = 12;

  // Add more photos
  $('#addmorephotos').click(function () {
    addPhotoField();
  });
  // Add more Text
  $('#addmoretext').click(function () {
    addTextField();
  });
  // REMOVE BUTTONS
  // Remove last photo
  $("#removelastphoto").click(function () {
    canvas.remove(photoCan[photonum-1]);//remove from canvas
    $('#userphotogrp'+(photonum-1)).remove(); //remove from options
    photonum--; //subtract the number
    if(photonum<=1) $("#removelastphoto").hide(); //remove the button if less than num
  });
  // Remove last Text
  $("#removelasttext").click(function () {
    canvas.remove(textCan[textnum-1]);//remove textarea from canvas
    $('#textgrp'+(textnum-1)).remove(); //remove from options
    textnum--; //subtract the number
    if(textnum<=1) $("#removelasttext").hide(); //remove the button if less than num
  });
  //checked or unchecked photos checkbox
  $('#addPhotosCheck').change(function() {
        if(this.checked) {
            //checked
            addPhotoField();
            $("#addmorephotos").show();
        } else {
          //unchecked
          var returnVal = confirm("This will remove the entered data?");
            $(this).prop("checked", !returnVal);
            if(returnVal) {
              $('#photoslist').html(''); //remove all divs inside list
              $("#addmorephotos").hide();
               $("#removelastphoto").hide(); //remove remove button
              for(var k=0; k<phototot ; k++) {
                canvas.remove(photoCan[k]); //Remove all photos from canvas
              }
              photonum = 0; //reset value of photo number
            }
        }      
    });
  //checked or unchecked BG checkbox
  $('#addBgCheck').change(function() {
        if(this.checked) {
            $("#myDropzonef").show();
            $(".morfchoice").show();

        } else {
          $("#myDropzonef").hide(); //*********************************also delete the female files
          $(".morfchoice").hide();
        }      
    });
  //checked or unchecked Text checkbox
  $('#addTextCheck').change(function() {
        if(this.checked) {
            //checked
            addTextField();
            $("#addmoretext").show();
        } else {
          //unchecked
          var returnVal = confirm("This will remove the entered data?");
            $(this).prop("checked", !returnVal);
            if(returnVal) {
              $('#textlist').html(''); //remove all divs inside list
              $("#addmoretext").hide();
              $("#removelasttext").hide(); //remove remove button
              for(var k=0; k<texttot ; k++) {
                canvas.remove(textCan[k]); //Remove all photos from canvas
              }
              textnum = 0; //reset value of photo number
            }
        }      
    });


  function addPhotoField(){
    if(photonum<phototot) {
       $('#photoslist').append(`<div class="well"><div class="form-group" id="userphotogrp`+photonum+`" ><hr><h2>`+(photonum+1)+`</h2>
          <label for="userphoto`+photonum+`">Photo type</label>
          <select class="form-control userphotos" id="userphoto`+photonum+`">
            <option>User Photo</option>
            <option>Friend Photo</option>
            <option>Friend Photo (Opposite gender)</option>
          </select>
        </div></div>`);
         canvas.add(photoCan[photonum]); // add photo to canvas
         if(photonum>0) {$("#removelastphoto").show(); }//show the "remove last" button
         photonum++;
     } else {
        alert("You can only add upto "+phototot+ " Photos");
    }
  }
  function addBgField(){
    if(bgnum<bgtot) {
        $('#backgroundlist').append(`<div class="well">
      <div class="form-group" id="bggrp`+bgnum+`" ><hr><h2>`+(bgnum+1)+`</h2>
        <label for="bg`+bgnum+`">Upload an image</label>
        <input type="file" class="form-control-file" id="bg`+bgnum+`" aria-describedby="fileHelp">
        <small id="fileHelp" class="form-text text-muted">Prefered resolution is 800x420px</small>
      </div>
      <div class="form-group">
          <label for="userphotos">Show to:</label>
          <select class="form-control userphotos" id="userphotos">
            <option>Common</option>
            <option>Male</option>
            <option>Female</option>
          </select>
        </div></div>`);
        if(bgnum>0) $("#removelastbg").show();
        bgnum++;
    } else {
      alert("You can only add upto "+bgtot+ " Backgrounds");
    }
  }
  function addTextField(){
    if(textnum<texttot) {
      $('#textlist').append(`<div class="well">
      <div class="form-group" id="textgrp`+textnum+`" ><hr><h2>`+(textnum+1)+`</h2>
        <label for="text`+textnum+`">Add text line by line</label>
        <textarea class="form-control" id="text`+textnum+`" rows="3"></textarea>
      </div>
      <div class="form-group">
          <label for="showto`+textnum+`">Show to:</label>
          <select class="form-control userphotos" id="showto`+textnum+`">
            <option>Common</option>
            <option>Male</option>
            <option>Female</option>
          </select>
        </div>
        <div class="form-group">
          <label for="style`+textnum+`">Text Style:</label>
          <select class="form-control chosen-select" id="style`+textnum+`">
          <?php foreach($styles as $style) {
            echo "<option>$style[0]</option>\n";
          } ?>
          </select>
        </div></div>`);
      $(".chosen-select").chosen(); //change select fields to chosen
      $('.chosen-container').css('width', '100%'); //some bug fix for chosenjs
      canvas.add(textCan[textnum]); // add photo to canvas
      if(textnum>0) $("#removelasttext").show();
      textnum++;
    } else {
      alert("You can only add upto "+texttot+ " TextFields");
    }
  }
 //SUBMIT CODE AJAX
  $("#finalSubmit").click(function () {
      $(".overlay").show(); //show loading
      var formData = new Object();
      formData.slug = slug; //set slug to post variable
      formData.photos = {};
      formData.text = {};
      formData.token = "<?php echo $token; ?>";
      var numofphotos = photonum;
      var numoftext = textnum;
      var phototype = 0; // type of photo -> [user,friend,opp gender friend] => [0,1,2]
      var textshowto = 0; // whom to show the text -> [common, male, female] => [0,1,2]
      var textval = ""; //value of text field
      var textstyle = ""; //value of text style
      var x,y,h,w,str = "";
      //photos
      for(var i =0 ; i < numofphotos ; i++ ) {
        phototype = document.getElementById("userphoto"+i).selectedIndex;
        x = Math.floor(photoCan[i].left);
        y = Math.floor(photoCan[i].top);
        w = Math.floor(photoCan[i].getWidth());
        h = Math.floor(photoCan[i].getHeight());
        str = phototype + "," + x + "," + y + "," + w + "," + h;
        formData.photos[i] = str;
      }
      //text
      for(var i =0 ; i < numoftext ; i++ ) {
        textshowto = document.getElementById("showto"+i).selectedIndex;
        textval = document.getElementById("text"+i).value;
        textval = textval.trim(); //remove leading or trailing whitespaces
        textstyle = $("#style"+i+" option:selected").val();
        x = Math.floor(textCan[i].left);
        y = Math.floor(textCan[i].top);
        w = Math.floor(textCan[i].getWidth());
        h = Math.floor(textCan[i].getHeight());
        str = textstyle + "," + textshowto + "," + x + "," + y + "," + w + "," + h;
        formData.text[i] = {"value" : textval, "prop" : str};
      }
      var dataToSend = JSON.stringify(formData);
      console.log(dataToSend);
      $.ajax({
          url: 'edit-ajax.php',
          type: 'POST',
          data:  {"data" : dataToSend},
          success: function( data, textStatus, jQxhr ){
              $(".overlay").hide();
          },
          error: function( jqXhr, textStatus, errorThrown ){
              console.log( errorThrown );
          }
      });
  });
  //Load from previous
  $(".overlay").show();
  <?php 
  //load pre photos
  $i = 0;
  $prop = Array();
  foreach ($photos as $photo) {
    $prop = str_getcsv($photo["prop"]);
    echo "$('#addPhotosCheck').prop('checked', true);";
    echo '$("#addmorephotos").show();';
    echo 'photoCan['.$i.'].top = '.$prop[2].';';
    echo 'photoCan['.$i.'].left = '.$prop[1].';';
    echo 'photoCan['.$i.'].scaleToHeight('.$prop[4].');';
    echo 'photoCan['.$i.'].scaleToWidth('.$prop[3].');';
    echo 'addPhotoField();';
    echo 'document.getElementById("userphoto'.$i.'").selectedIndex = '.$prop[0].";";
    $i++;
  }
  ?>

  <?php
  $i = 0;
  $prop = Array();
  foreach ($text as $txt) {
    $prop = str_getcsv($txt["prop"]);
    echo "$('#addTextCheck').prop('checked', true);";
    echo '$("#addmoretext").show();';
    echo 'textCan['.$i.'].top = '.$prop[3].';';
    echo 'textCan['.$i.'].left = '.$prop[2].';';
    echo "textCan[{$i}].setScaleX({$prop[4]}/textCan[{$i}].getWidth());";
    echo "textCan[{$i}].setScaleY({$prop[5]}/textCan[{$i}].getHeight());";

    echo 'addTextField();';
    echo 'document.getElementById("showto'.$i.'").selectedIndex = '.$prop[1].";";
    echo '$("#style'.$i.'").val("'.$prop[0].'");';
    echo '$(".chosen-select option:contains(Base)").prop("selected","selected");';
    echo '$(".chosen-select").trigger("chosen:updated");';
    echo '$("#text'.$i.'").text(`'.$txt['data'].'`);';
    $i++;
  }
  ?> 
  canvas.renderAll();
  $(".overlay").hide();//stop loading


}); //document.ready end


</script>

如何将旋转的图像和文本坐标保存到数据库并以相同的角度打印图像?我正在尝试将图像保存为文本并显示在结果图像中。

javascript jquery arrays fabricjs
1个回答
0
投票

使用canvas.toJSON()它会将所有画布数据转换为json。将该数据发送到db。当从db加载时使用canvas.loadFromJSON()。您无需存储数组中的数据并加载它。

© www.soinside.com 2019 - 2024. All rights reserved.