如何下载带有背景图像和前景图像的画布?

时间:2019-03-25 13:37:40

标签: javascript css3 html5-canvas

我正在设计一个带有背景图像的“画布”,并向前景添加多个图像和文本,但是当我单击“保存”按钮时,它将 仅下载前景图像。我正在使用fabric.min.js添加文本和图像。

我尝试了两天,但无法下载带有背景和前景图像的画布。

// Change active class on product sizes.

var sizes = jQuery(".product--size").find("span");
sizes.click(function() {
  sizes.removeClass("active");
  $(this).addClass("active");
});

// Change image on thumbnail click.
var thumbs = $(".icon-images").find("img");
thumbs.click(function() {
  var src = $(this).attr("src");
  var dp = $(".display-img");
  dp.attr("src", src);
});

// drag and drop

var canvas = new fabric.Canvas('c');

function insertShape() {
// create a rectangle with angle=45
var rect = new fabric.Rect({
  left: 100,
  top: 100,
  fill: 'red',
  width: 20,
  height: 20,
});
canvas.add(rect);
}

function insertText() {
  var text = new fabric.IText('Enter Your Text', { left: 40, top: 100 });
  canvas.add(text);
}

function addHandler(id, fn, eventName) {
  document.getElementById(id)[eventName || 'onclick'] = function() {
    var el = this;
    if (obj = canvas.getActiveObject()) {
      fn.call(el, obj);
      canvas.renderAll();
    }
  };
}

function setStyle(object, styleName, value) {
  if (object.setSelectionStyles && object.isEditing) {
    var style = { };
    style[styleName] = value;
    object.setSelectionStyles(style);
  }
  else {
    object[styleName] = value;
  }
}

function getStyle(object, styleName) {
  return (object.getSelectionStyles && object.isEditing)
    ? object.getSelectionStyles()[styleName]
    : object[styleName];
}

  // select font style

  // $(function(){
  //   $('#font').fontselect().change(function(){

  //     // replace + signs with spaces for css
  //     var font = $(this).val().replace(/\+/g, ' ');

  //     // split font into family and weight
  //     font = font.split(':');

  //     // set family on paragraphs 
  //     $('#c').get(0).css('font-family', font[0]);
  //   });
  // });

addHandler('underline', function() {
  var isUnderline = getStyle(obj, 'textDecoration') === 'underline';
  setStyle(obj, 'textDecoration', isUnderline ? '' : 'underline');
});

addHandler('bold', function() {
  var isBold = getStyle(obj, 'fontWeight') === 'bold';
  setStyle(obj, 'fontWeight', isBold ? '' : 'bold');
});

addHandler('italic', function() {
  var isItalic = getStyle(obj, 'fontStyle') === 'italic';
  setStyle(obj, 'fontStyle', isItalic ? '' : 'italic');
});

addHandler('centered', function() {
  var isCentered = getStyle(obj, 'textAlign') === 'center';
  setStyle(obj, 'textAlign', isCentered ? '' : 'center');
});

addHandler('left', function() {
  var isLeft = getStyle(obj, 'textAlign') === 'left';
  setStyle(obj, 'textAlign', isLeft ? '' : 'left');
});

addHandler('right', function() {
  var isRight = getStyle(obj, 'textAlign') === 'right';
  setStyle(obj, 'textAlign', isRight ? '' : 'right');
});

addHandler('size', function(obj) {
  setStyle(obj, 'fontSize', parseInt(this.value, 10));
}, 'onchange');

addHandler('height', function(obj) {
  setStyle(obj, 'lineHeight', parseInt(this.value, 10));
}, 'onchange');

addHandler('color', function(obj) {
  setStyle(obj, 'fill', this.value);
}, 'onchange');

addHandler('bg-color', function(obj) {
  setStyle(obj, 'textBackgroundColor', this.value);
}, 'onchange');




function deleteObjects(){
    var activeObject = canvas.getActiveObject(),
    activeGroup = canvas.getActiveGroup();
    if (activeObject) {
        if (confirm('Are you sure you want delete the selected object!!!')) {
            canvas.remove(activeObject);
        }
    }
    else if (activeGroup) {
        if (confirm('Are you sure you want delete the selected object!!!')) {
            var objectsInGroup = activeGroup.getObjects();
            canvas.discardActiveGroup();
            objectsInGroup.forEach(function(object) {
            canvas.remove(object);
            });
        }
    }
}

//upload image

document.getElementById('imgLoader').onchange = function handleImage(e) {
var reader = new FileReader();
  reader.onload = function (event){
    var imgObj = new Image();
    imgObj.src = event.target.result;
    imgObj.onload = function () {
      var image = new fabric.Image(imgObj);
      image.set({
            angle: 0,
            padding: 10,
            cornersize:10,
            height:110,
          width:110
      });
      canvas.centerObject(image);
      canvas.add(image);
      canvas.renderAll();
    }
  }
  reader.readAsDataURL(e.target.files[0]);
}

function onObjectSelected(e) {
  if ((e.target.get('type')) === "i-text") {
    document.getElementById("textMenu").className = "displayOperations";
  } else {
    // do nothing.
  }
}
canvas.on('object:selected', onObjectSelected);

canvas.on('before:selection:cleared', function() {
  document.getElementById("textMenu").className = "hideOperations";
});


// Zoom-In & Zoom-Out

var imagesize = $('#c').width();

$('.zoomout').on('click', function(){
    imagesize = imagesize - 20;
    $('#c').width(imagesize);
});

$('.zoomin').on('click', function(){
    imagesize = imagesize + 20;
    $('#c').width(imagesize);
});

// set image in to canvas
// var canvas = document.getElementById('c'),
// context = canvas.getContext('2d');

// make_base();

// function make_base()
// {
//   base_image = new Image();
//   base_image.src = './images/border1.jpg';
//   base_image.onload = function(){
//     context.drawImage(base_image, 0, 0);
//   }
// }

// download images

  // $('#btn_download').click(function(){
  //   $('#c').get(0).toBlob(function(blob){
  //     saveAs(blob, "myIMG.png");
  //   })
  // });


  // preview 
  $(document).ready(function(){

  $(".icon-images > img").click(function () {
      var img = $(this).attr('src');
      $('#c').css("background-image", "url(" + img + ")");
  });

  var element = $("#editor1"); // global variable
  var getCanvas; // global variable

    $("#btn-Preview-Image").one('click', function () {
          html2canvas(element, {
          onrendered: function (canvas) {
                $("#previewImage").append(canvas);
                getCanvas = canvas;
            }
        });
    });

    $("#btn-Convert-Html2Image").on('click', function () {
      var imgageData = getCanvas.toDataURL("image/png");
      // Now browser starts downloading it instead of just showing it
      var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream");
      $("#btn-Convert-Html2Image").attr("download", "img.png").attr("href", newData);
    });

  });

  // click on anchor tag to download image

  function download() {
    var dt = canvas.toDataURL('image/png');
    this.href = dt;
  };
  download_img.addEventListener('click', download, true);


// var myCanvas = document.querySelector('c'),     
//     img = document.createElement('img'),    
//     ctx = myCanvas.getContext ? myCanvas.getContext('2d') : null;

//     myCanvas.width = window.innerWidth;
//     myCanvas.height = window.innerHeight;
//     img.onload = function () {  
//         ctx.drawImage(img, 0, 0, myCanvas.width, myCanvas.height);
//     };
// img.src = 'image.png';
$('#btn_download').click(function(){
  var x = document.getElementById('previewImage').innerHTML;
})
.display-img{
  width: 100%;
  height: 100%;
  /* border: 1px solid #ddd; */
}
.product--image{
  float: left;
  width: 45%;
}
.product--image {
  padding-right: 3%;
}
.product--image .icon-images{
  display: flex;
}
.product--image .icon-images img {
  width: 100px;
  height: 90px;
  margin-right:15px;
  margin-bottom: 15px;
  cursor: pointer;
  border: 1px solid #e5e5e5;
}
@media screen and (max-width: 500px) {
  .product--image, .product--details {
    float: none;
    width: 100%;
    padding: 10px 5px;
    margin: 5px 10px;
  }
}
a:not([href]):not([tabindex]){
  width:100px;
}
#color, #bg-color, #colorpicker{
  border-radius: 4px;
  height: 34px;
  width: 100px;
  margin:2px 0px;
}
#imgLoader{
  border-radius: 4px;
  background-color: #aaa;
  width: 100px;
  height: 34px;
  padding: 2px;
  margin-bottom:2px;
}
.btn2{
  white-space: nowrap;
  width: 100px;
  margin: 2px 0px;
}

/* drag and drop */
/* input[type="file"] {
  display: none;
} */
/* .custom-file-upload {
  border: 1px solid #ccc;
  display: inline-block;
  padding: 4px 7px;
  cursor: pointer;
  border-radius: 5px;
  background-color: #aaa;
  color: #fff;
} */

.hideOperations {
  display: none;
}

.displayOperations {
  display: block;
}

.editor-area {
  overflow: hidden;
  float: left;
  border: 2px dashed #aaa;
  padding-bottom: 30px;
  background-color: #fff;
}
.edit_area{

  margin-bottom: 30px;
  padding-top: 15px;
  padding-bottom: 15px;
  border: 1px solid #bac0c1;
}
.controls {
  width: 100px;
  overflow: hidden;
  float: right;
  position: relative;
}

.canvas-bg-wrapper {
  position: relative;
  width: 540px;
  height: 570px;
}

.canvas-bg {
  position: absolute;
}
/* 
.canvas-container {
  border-style: dashed;

} */
#btn_download, #btn-Preview-Image{
  margin-top: 15px;
}

#c {
  position: relative;
  background-color: #fff;
  background-image:url(../images/back.jpg);
  background-repeat:no-repeat;
  background-size:89%;
}
.modal-dialog {
  max-width: 560px;
}
.background-img{
  background-image: url(../images/xy.jpg);
  background-position: center;
  width: 100%;
  background-repeat: no-repeat;
}
<!DOCTYPE html>
<html lang="en" >
<head>
    <meta charset="UTF-8">
    <title>Product Design page</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" type="text/css" href="css/fontselect-default.css" />
</head>
<body>
<div class="background-img">
  <div class="container">
    <div class="row edit_area">
      <div class="col-md-6 col-sm-6 col-xs-12">
          <div class="product">
            <div class="product--body">
              <div class="product--image">
                <div class="icon-images">
                  <img src="images/back1.jpg" title="Front Side"/>
                  <img src="images/front1.jpg" title="Back Side"/>
                  <img src="images/back.jpg" title="Left Side"/>
                  <img src="images/front.jpg" title="Right Side"/>
                </div>
                <div id="canvas-wrapper" class="editor-area">
                  <div class="canvas-bg-wrapper" id="editor1" style="background-color: #ffffff;">
                    <!-- <a href="images/front1.jpg" download>
                        <img class="canvas-bg display-img" id="img1" alt="big-image" src="images/front1.jpg">
                    </a> -->
                      <canvas width="600" height="560" id="c" ></canvas>
                  </div>
                </div>
                <!-- <button class="btn btn-success btn-sm" id="btn_download">Download</button> -->
                <input id="btn-Preview-Image" class="btn btn-success btn-sm" type="button" value="Preview" data-toggle="modal" data-target="#myModal"/>
                <br/>

            </div>
          </div>
        </div>
      </div>
      <div class="col-md-6 col-sm-6 col-xs-12">
        <div class="controls">
            <!-- <label for="file-upload" title="Upload Image" class="custom-file-upload">
                <i class="fa fa-cloud-upload"></i>
            </label> -->
            <input type="file" id="imgLoader"><br>
              <button class="btn btn-info btn-sm btn2" title="Insert Text" onClick="insertText()">Insert Text <i class="fa fa-pencil-square-o" aria-hidden="true"></i></button>
              <div id="textMenu" class="hideOperations">
                <input type="range" min="5" max="150" value="40" id="size">
                <input type="range" min="0.1" max="5" value="0.1" id="height">
                <input type="color" id="color" title="Change Color">
                <input type="color" id="bg-color" title="Change Background Color">
                <!-- <input id="font" type="text" style="float:left"/> -->
                <button class="btn btn-secondary btn-sm btn2" id="italic" title="Italic">Italic <i class="fa fa-italic" aria-hidden="true"></i></button>
                <button class="btn btn-secondary btn-sm btn2" id="centered" title="Align Center">Center <i class="fa fa-align-center" aria-hidden="true"></i></button>
                <button class="btn btn-secondary btn-sm btn2" id="left" title="Align Left">Align Left <i class="fa fa-align-left" aria-hidden="true"></i></button>
                <button class="btn btn-secondary btn-sm btn2" id="right" title="Align Right">Align Right <i class="fa fa-align-right" aria-hidden="true"></i>
                <button id="underline" class="btn btn-secondary btn-sm btn2" title="Underline">Underline <i class="fa fa-underline" aria-hidden="true"></i></button>
                <button id="bold" class="btn btn-secondary btn-sm btn2" title="Bold">Bold <i class="fa fa-bold" aria-hidden="true"></i></button>
                </button>
              </div>
              <!-- <button class="btn btn-warning btn-sm" onClick="insertShape()">Insert Shape</button> -->
              <button class="btn btn-danger btn-sm btn2" title="Delete Selected Object" onClick="deleteObjects()">Delete <i class="fa fa-trash-o" aria-hidden="true"></i></button>
              <div>
                <button class="btn btn-sm btn-info zoomin btn2" title="Zoom-in">Zoom-in <i class="fa fa-search-plus" aria-hidden="true"></i></button> 
                <button class="btn btn-sm btn-secondary zoomout btn2" title="Zoom-out">Zoom-out <i class="fa fa-search-minus" aria-hidden="true"></i></button>
              </div>
          </div>
      </div>
    </div>
    <div class="row">
      <div class="col-md-12">
          <div class="modal" id="myModal">
              <div class="modal-dialog modal-lg">
                <div class="modal-content">

                  <!-- Modal Header -->
                  <div class="modal-header">
                    <h4 class="modal-title">Preview Image</h4>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                  </div>

                  <!-- Modal body -->
                  <div class="modal-body">
                    <p style="color: red;">Right Click -> Save image...</p>
                    <a href="#" download="custom-filename.png" id="download_img" >
                      <div id="previewImage"></div>
                    </a>
                  </div>

                  <!-- Modal footer -->
                  <div class="modal-footer">
                    <button id="btn-Convert-Html2Image" class="btn btn-success">Download</button>
                    <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
                    <button id="btn_download" class="btn btn-warning">Download</button>
                    <button id="to-svg">toSVG</button>
                  </div>
                </div>
              </div>
            </div>
      </div>
    </div>
  </div>
</div>
  <script src="https://files.codepedia.info/files/uploads/iScripts/html2canvas.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/sketch.js/1.0/sketch.min.js"></script>
  <script src="http://intridea.github.io/sketch.js/lib/sketch.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js" type="text/javascript"></script>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.5/fabric.min.js'></script>
  <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script> -->
  <script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.debug.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/canvas2image@1.0.5/canvas2image.js"></script>
  <script src="js/FileSaver.min.js"></script>
  <script src="js/canvas-toBlob.js"></script>
  <script src="js/script.js"></script>

</body>
</html>
 $('#btn_download').click(function(){
     $('#c').get(0).toBlob(function(blob){
       saveAs(blob, "myIMG.png");
     })
});

我希望输出是下载包含背景图像的画布。

0 个答案:

没有答案