在下载的HTML5画布PNG上未呈现背景图像

时间:2018-02-20 10:05:10

标签: jquery canvas fabricjs

我有3个输入背景图像,可以更改onclick并填充画布区域。我通过文件输入上传其他图像,将其放置在bg图像的顶部。当我将画布保存为PNG时,所有图像 - 除了背景图像 - 都会被渲染。我希望画布上的所有图像都渲染并保存到PNG。

对此的任何见解将不胜感激: - )

jsfiddle

的javascript:

// Buttons onclick change background image of canvas
$(document).ready(function() {
  $("#canvascolor > input").click(function() {
    var img = $(this).attr('src');
    $('#myCanvas').css("background-image", "url(" + img + ")");
  });
});
// END Buttons onclick background image of canvas

var canvas = new fabric.Canvas('myCanvas', {
  backgroundColor: 'transparent'
});

function renderImage(e) {
  var imgUrl = URL.createObjectURL(e.target.files[0]);
  fabric.Image.fromURL(imgUrl, function(img) {
    // set default props
    img.set({
      width: 150,
      height: 150,
      top: 75,
      left: 75,
      transparentCorners: false
    });
    canvas.add(img);
    canvas.renderAll();
  });
}

function saveOnPC() {
  var link = document.createElement('a');
  link.href = canvas.toDataURL();
  link.download = 'myImage.png';
  link.click();
}

function click(el) {
  // Simulate click on the element.
  var evt = document.createEvent('Event');
  evt.initEvent('click', true, true);
  el.dispatchEvent(evt);
}

document.querySelector('#fileSelect').addEventListener('click', function(e) {
  var fileInput = document.querySelector('#fileElem');
  //click(fileInput); // Simulate the click with a custom event.
  fileInput.click(); // Or, use the native click() of the file input.
}, false);

$('#remove').click(function() {
  var object = canvas.getActiveObject();
  if (!object) {
    alert('Please select the element to remove');
    return '';
  }
  canvas.remove(object);
});

HTML:

<canvas id="myCanvas" width="400" height="800"></canvas>
<section id="canvascolor">
   <input id="bostonblue" class="canvasborder" type="image" src="https://s26.postimg.org/i3ibods55/blue.jpg">
   <input id="bostonblack" class="canvasborder" type="image" src="https://s26.postimg.org/vlp803yzd/black.jpg">
   <input id="bostonamber" class="canvasborder" type="image" src="https://s26.postimg.org/o5pyeao4p/amber.jpg">
 </section>

1 个答案:

答案 0 :(得分:0)

不是通过css设置背景图像,而是使用canvas.setBackgroundImage()

设置画布的背景图像
$("#canvascolor > input").click(function () {
    var img = $(this).attr('src');
    canvas.setBackgroundImage(img,canvas.renderAll.bind(canvas));
});