更新 canvas 输入类型文件 jCanvas 中的图像

Update images in canvas input type file jCanvas

我正在使用 jCanvas 制作带有 jQuery 的传单编辑器:https://projects.calebevans.me/jcanvas/

$(function () {
  initCanvas();

  $.datepicker.regional['fr'] = {
    closeText: 'Fermer',
    prevText: '<Préc',
    nextText: 'Suiv>',
    currentText: 'Aujourd\'hui',
    monthNames: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Aout', 'Septembre', 'Octobre', 'Novembre', 'Décembre'],
    monthNamesShort: ['Jan', 'Fev', 'Mar', 'Avr', 'Mai', 'Jun', 'Jul', 'Aou', 'Sep', 'Oct', 'Nov', 'Dec'],
    dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
    dayNamesShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
    dayNamesMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'],
    weekHeader: 'Sm',
    dateFormat: 'dd-mm-yy',
    firstDay: 1,
    isRTL: false,
    showMonthAfterYear: false,
    yearSuffix: '',
    minDate: 0,
    maxDate: '+12M +0D',
    numberOfMonths: 2,
    showButtonPanel: true
  };

  $.datepicker.setDefaults($.datepicker.regional['fr']);
  $("#date_input").on("change", function () {
    $(this).css("color", "rgba(0,0,0,0)").siblings(".datepicker_label").css({
      "text-align": "center",
      position: "absolute",
      left: "140px",
      top: "40px",
      width: $(this).width()
    }).text($(this).val().length == 0 ? "" : ($.datepicker.formatDate($(this).attr("dateformat"), new Date($(this).val()))));
  });

  $('form').on('keyup change paste', 'input, select, textarea', function () {
    console.log("hola datevid");
    updateCanvasTEXT();
  });

  $('#pic_broadcaster').on("change", function () {
    if (this.files && this.files[0]) {
      var reader = new FileReader();

      reader.onload = function (e) {
        console.log(e.target.result);
        updateCanvasIMG(e.target.result, '');
      }

      reader.readAsDataURL(this.files[0]);
    }
  });

  $('#pic_challenger').on("change", function () {
    if (this.files && this.files[0]) {
      var reader = new FileReader();

      reader.onload = function (e) {
        console.log(e.target.result);
        updateCanvasIMG('', e.target.result);
      }

      reader.readAsDataURL(this.files[0]);
    }
  });
});

function updateCanvasIMG(pic_broadcaster = "https://i.ibb.co/qNP921b/IMG-0146.jpg", pic_challenger = "https://i.ibb.co/hHDj50p/S-3629060.jpg") {
  if (pic_broadcaster.indexOf('data:') !== -1) {
    console.log('pic_broadcaster contains data:');
  } else {
    console.log('pic_broadcaster not contains data:');
  }

  $('#canvas').setLayer('photo_bc', {
    type: 'image',
    source: pic_broadcaster,
    x: 42,
    y: 332,
    width: 334,
    height: 334,
    fromCenter: false
  }).setLayer('photo_challenger', {
    type: 'image',
    source: pic_challenger,
    x: 625,
    y: 332,
    width: 334,
    height: 334,
    fromCenter: false
  }).setLayer('fond_canvas', {
    type: 'image',
    source: 'https://i.ibb.co/FwkgQ2n/fond.png',
    x: 0,
    y: 0,
    width: 1000,
    height: 1000,
    fromCenter: false
  }).drawLayers();
}

function updateCanvasTEXT() {
  $('#canvas').setLayer('pseudo_bc', {
    type: 'text',
    fillStyle: '#fff',
    x: 150,
    y: 715,
    fontSize: 35,
    fontFamily: 'Verdana, sans-serif',
    maxWidth: 300,
    align: 'left',
    respectAlign: true,
    text: $('#bc_agency').val()
  }).setLayer('pseudo_challenger', { // pseudo challenger
    type: 'text',
    fillStyle: '#fff',
    x: 710,
    y: 715,
    fontSize: 35,
    fontFamily: 'Verdana, sans-serif',
    maxWidth: 300,
    align: 'left',
    respectAlign: true,
    text: $('#bc_challenger').val()
  }).setLayer('date_time', { // date et heure
    type: 'text',
    fillStyle: '#fff',
    fontStyle: 'bold',
    x: 500,
    y: 820,
    fontSize: 45,
    fontFamily: 'Verdana, sans-serif',
    text: $('.datepicker_label').text() + " à " + $('.event_heure').val().replace(":", "h")
  }).drawLayers();
}

function initCanvas() {
  $('#canvas').addLayer({ // photo bc
    name: 'photo_bc',
    type: 'image',
    source: "https://i.ibb.co/qNP921b/IMG-0146.jpg",
    x: 42,
    y: 332,
    width: 334,
    height: 334,
    fromCenter: false
  }).addLayer({ // photo adversaire
    name: 'photo_challenger',
    type: 'image',
    source: "https://i.ibb.co/hHDj50p/S-3629060.jpg",
    x: 625,
    y: 332,
    width: 334,
    height: 334,
    fromCenter: false
  }).addLayer({ // fond
    name: 'fond_canvas',
    type: 'image',
    source: 'https://i.ibb.co/FwkgQ2n/fond.png',
    x: 0,
    y: 0,
    width: 1000,
    height: 1000,
    fromCenter: false
  }).addLayer({ // pseudo bc 
    name: 'pseudo_bc',
    type: 'text',
    fillStyle: '#fff',
    x: 150,
    y: 715,
    fontSize: 35,
    fontFamily: 'Verdana, sans-serif',
    maxWidth: 300,
    align: 'left',
    respectAlign: true,
    text: $('#bc_agency').val()
  }).addLayer({ // pseudo challenger
    name: 'pseudo_challenger',
    type: 'text',
    fillStyle: '#fff',
    x: 710,
    y: 715,
    fontSize: 35,
    fontFamily: 'Verdana, sans-serif',
    maxWidth: 300,
    align: 'left',
    respectAlign: true,
    text: $('#bc_challenger').val()
  }).addLayer({ // date et heure
    name: 'date_time',
    type: 'text',
    fillStyle: '#fff',
    fontStyle: 'bold',
    x: 500,
    y: 820,
    fontSize: 45,
    fontFamily: 'Verdana, sans-serif',
    text: $('.datepicker_label').text() + " à " + $('.event_heure').val().replace(":", "h")
  }).drawLayers();
}
.canvas{width: 97vw;height: 60vh;max-width: 1000px;max-height: 1000px;}
#date_input{text-indent: -500px;height:25px; width:200px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/123941/jcanvas.15.12.12.min.js"></script>
<form>
  <label class="bc_agency" for="input">Pseudo broadcaster: </label>
  <input type="text" name="bc_agency" id="bc_agency" placeholder="Entrer votre pseudo" value="Pseudo">
  <label class="bc_challenger" for="input">Pseudo advsersaire: </label>
  <input type="text" name="bc_challenger" id="bc_challenger" placeholder="Entrer le pseudo de l'adversaire" value="Pseudo"><br>
  Date de l'évévement <input type="date" name="pk_date" dateformat="DD d MM" id="date_input"><span class="datepicker_label" style="pointer-events: none;"></span> Heure <input type="time" name="event_heure" class="event_heure"><br>
  Photo broadcaster: <input type="file" name="pic_broadcaster" id="pic_broadcaster"><br>
  Photo adversaire: <input type="file" name="pic_challenger" id="pic_challenger"><br>
</form>
<br>
<canvas id="canvas" width="1000" height="1000">
  <p>This is fallback content for users of assistive technologies or of browsers that don't have full support for the Canvas API.</p>
</canvas>

在我的 javascript 中,首先我调用我的函数 initCanvas() 来向 canvas 添加图层,它在页面加载时运行良好。

正如您在我的演示中看到的那样,您可以更改文本、日期和时间,但是当您想使用 setLayer() 函数更改图像时,背景和所有内容 运行 都会消失...

我试了好几个小时还是不行。

感谢您的帮助。

在你当前的代码中,你只在 updateCanvasIMG 中发送一个值,所以另一个值返回 null 并且没有在下面的代码中加载 image.Instead 我已经声明了 2 个变量来保存 pic_broadcasterpic_challenger 并检查该值是否不为空。如果另一个文件的值为空,则将默认图像 url 发送到您的函数 updateCanvasIMG.

演示代码 :

$(function() {
  initCanvas();

  $.datepicker.regional['fr'] = {
    closeText: 'Fermer',
    prevText: '<Préc',
    nextText: 'Suiv>',
    currentText: 'Aujourd\'hui',
    monthNames: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Aout', 'Septembre', 'Octobre', 'Novembre', 'Décembre'],
    monthNamesShort: ['Jan', 'Fev', 'Mar', 'Avr', 'Mai', 'Jun', 'Jul', 'Aou', 'Sep', 'Oct', 'Nov', 'Dec'],
    dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
    dayNamesShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
    dayNamesMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'],
    weekHeader: 'Sm',
    dateFormat: 'dd-mm-yy',
    firstDay: 1,
    isRTL: false,
    showMonthAfterYear: false,
    yearSuffix: '',
    minDate: 0,
    maxDate: '+12M +0D',
    numberOfMonths: 2,
    showButtonPanel: true
  };

  $.datepicker.setDefaults($.datepicker.regional['fr']);
  $("#date_input").on("change", function() {
    $(this).css("color", "rgba(0,0,0,0)").siblings(".datepicker_label").css({
      "text-align": "center",
      position: "absolute",
      left: "140px",
      top: "40px",
      width: $(this).width()
    }).text($(this).val().length == 0 ? "" : ($.datepicker.formatDate($(this).attr("dateformat"), new Date($(this).val()))));
  });

  $('form').on('keyup change paste', 'input, select, textarea', function() {
    console.log("hola datevid");
    updateCanvasTEXT();
  });
  var file1 = "";
  var file2 = "";

  $('#pic_broadcaster').on("change", function() {
    if (this.files && this.files[0]) {
      var reader = new FileReader();

      reader.onload = function(e) {
        console.log(e.target.result);
        file1 = e.target.result;
        //checking if file2 is not null
        if (file2 != "") {
        //send same
          updateCanvasIMG(file1, file2);
        } else {
        //send default image
          updateCanvasIMG(file1, "https://i.ibb.co/hHDj50p/S-3629060.jpg");
        }
      }

      reader.readAsDataURL(this.files[0]);
    }

  });


  $('#pic_challenger').on("change", function() {
    if (this.files && this.files[0]) {
      var reader = new FileReader();

      reader.onload = function(e) {
        console.log(e.target.result);
        file2 = e.target.result;
  //check if file1 is not null 
        if (file1 != "") {
        //send same to function
          updateCanvasIMG(file1, file2);
        } else {
        //send default image
          updateCanvasIMG("https://i.ibb.co/qNP921b/IMG-0146.jpg", file2);
        }
      }

      reader.readAsDataURL(this.files[0]);
    }
  });
});

function updateCanvasIMG(pic_broadcaster, pic_challenger) {

  $('#canvas').setLayer('photo_bc', {
    type: 'image',
    source: pic_broadcaster,
    x: 42,
    y: 332,
    width: 334,
    height: 334,
    fromCenter: false
  }).setLayer('photo_challenger', {
    type: 'image',
    source: pic_challenger,
    x: 625,
    y: 332,
    width: 334,
    height: 334,
    fromCenter: false
  }).setLayer('fond_canvas', {
    type: 'image',
    source: 'https://i.ibb.co/FwkgQ2n/fond.png',
    x: 0,
    y: 0,
    width: 1000,
    height: 1000,
    fromCenter: false
  }).drawLayers();
}

function updateCanvasTEXT() {
  $('#canvas').setLayer('pseudo_bc', {
    type: 'text',
    fillStyle: '#fff',
    x: 150,
    y: 715,
    fontSize: 35,
    fontFamily: 'Verdana, sans-serif',
    maxWidth: 300,
    align: 'left',
    respectAlign: true,
    text: $('#bc_agency').val()
  }).setLayer('pseudo_challenger', { // pseudo challenger
    type: 'text',
    fillStyle: '#fff',
    x: 710,
    y: 715,
    fontSize: 35,
    fontFamily: 'Verdana, sans-serif',
    maxWidth: 300,
    align: 'left',
    respectAlign: true,
    text: $('#bc_challenger').val()
  }).setLayer('date_time', { // date et heure
    type: 'text',
    fillStyle: '#fff',
    fontStyle: 'bold',
    x: 500,
    y: 820,
    fontSize: 45,
    fontFamily: 'Verdana, sans-serif',
    text: $('.datepicker_label').text() + " à " + $('.event_heure').val().replace(":", "h")
  }).drawLayers();
}

function initCanvas() {
  $('#canvas').addLayer({ // photo bc
    name: 'photo_bc',
    type: 'image',
    source: "https://i.ibb.co/qNP921b/IMG-0146.jpg",
    x: 42,
    y: 332,
    width: 334,
    height: 334,
    fromCenter: false
  }).addLayer({ // photo adversaire
    name: 'photo_challenger',
    type: 'image',
    source: "https://i.ibb.co/hHDj50p/S-3629060.jpg",
    x: 625,
    y: 332,
    width: 334,
    height: 334,
    fromCenter: false
  }).addLayer({ // fond
    name: 'fond_canvas',
    type: 'image',
    source: 'https://i.ibb.co/FwkgQ2n/fond.png',
    x: 0,
    y: 0,
    width: 1000,
    height: 1000,
    fromCenter: false
  }).addLayer({ // pseudo bc 
    name: 'pseudo_bc',
    type: 'text',
    fillStyle: '#fff',
    x: 150,
    y: 715,
    fontSize: 35,
    fontFamily: 'Verdana, sans-serif',
    maxWidth: 300,
    align: 'left',
    respectAlign: true,
    text: $('#bc_agency').val()
  }).addLayer({ // pseudo challenger
    name: 'pseudo_challenger',
    type: 'text',
    fillStyle: '#fff',
    x: 710,
    y: 715,
    fontSize: 35,
    fontFamily: 'Verdana, sans-serif',
    maxWidth: 300,
    align: 'left',
    respectAlign: true,
    text: $('#bc_challenger').val()
  }).addLayer({ // date et heure
    name: 'date_time',
    type: 'text',
    fillStyle: '#fff',
    fontStyle: 'bold',
    x: 500,
    y: 820,
    fontSize: 45,
    fontFamily: 'Verdana, sans-serif',
    text: $('.datepicker_label').text() + " à " + $('.event_heure').val().replace(":", "h")
  }).drawLayers();
}
.canvas {
  width: 97vw;
  height: 60vh;
  max-width: 1000px;
  max-height: 1000px;
}

#date_input {
  text-indent: -500px;
  height: 25px;
  width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/123941/jcanvas.15.12.12.min.js"></script>
<form>
  <label class="bc_agency" for="input">Pseudo broadcaster: </label>
  <input type="text" name="bc_agency" id="bc_agency" placeholder="Entrer votre pseudo" value="Pseudo">
  <label class="bc_challenger" for="input">Pseudo advsersaire: </label>
  <input type="text" name="bc_challenger" id="bc_challenger" placeholder="Entrer le pseudo de l'adversaire" value="Pseudo"><br> Date de l'évévement <input type="date" name="pk_date" dateformat="DD d MM" id="date_input"><span class="datepicker_label" style="pointer-events: none;"></span>  Heure <input type="time" name="event_heure" class="event_heure"><br> Photo broadcaster: <input type="file" name="pic_broadcaster" id="pic_broadcaster"><br> Photo adversaire: <input type="file" name="pic_challenger" id="pic_challenger"><br>
</form>
<br>
<canvas id="canvas" width="1000" height="1000">
  <p>This is fallback content for users of assistive technologies or of browsers that don't have full support for the Canvas API.</p>
</canvas>