簡體   English   中英

無法使用畫布和Javascript在圖像上繪制多個文本

[英]Could not draw multiple text on image using canvas and Javascript

我需要一個幫助。 我無法使用canvas和Javascript在畫布上繪制多個文本。 我在下面解釋我的代碼。

<div class="form-group">
<label for="exampleInputEmail1">Coupon Title</label>
<input type="text" name="emails" id="copTitle" class="form-control" placeholder="Add Coupon Title" value="<?php echo $email; ?>" required>
</div>

<div class="form-group">
<label for="coupondiscount">Coupon Discount</label>
<input name="coupondiscount" id="coupondiscount" class="form-control" placeholder="Add Coupon Discount" value="<?php echo $email; ?>" type="text"  required>
</div>
 <div class="couponimg" style="display:none;" id="blankImagediv">
<img class="img-responsive thumbnail" style="margin-bottom:9px; display:none;" src="images/coupon-banner-blank.jpg" crossorigin="anonymous" id="requiredImage">
<canvas id="canvas" class="img-responsive thumbnail" style="margin-bottom:9px;"></canvas>
</div>

我的javascript部分如下。

var canvas = document.getElementById('canvas'),
  img = document.getElementById('requiredImage'),
  ctx = canvas.getContext('2d');
  img.onload = drawImage;
  canvas.width = img.width;
  canvas.height = img.height;
  ctx.font = "26px Calibri";
  $(document).on('input', '#copTitle', function() {
      $('#blankImagediv').css('display', 'block');

      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(img, 0, 0);
      ctx.fillStyle = "#0D5F90";
      ctx.fillText($(this).val(), 160, 40);
  });
  $(document).on('input', '#coupondiscount', function() {
      console.log('hii');
      $('#blankImagediv').css('display', 'block');
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(img, 0, 0);
      ctx.fillStyle = "#0D5F90";
      ctx.fillText($(this).val(), 180, 90);
  });
  function drawImage()
  {
     ctx.drawImage(img, 0, 0);
  }

在這里,我需要用戶何時在第一個輸入字段上寫文本,它將寫在圖像的頂部,當用戶在第二個輸入字段上寫文本,它將寫在圖像的不同位置,但第一個文本不應替換。問題是每個文本都被替換為其他文本。請幫助我。

我認為原因是您每次都在清理畫布,然后繪制圖像,然后插入文本。 因此,它將刪除舊文本並添加新文本。 如果符合您的要求,請嘗試以下代碼,可能對您有幫助。

var canvas = document.getElementById('canvas'),
img = document.getElementById('requiredImage'),
ctx = canvas.getContext('2d');
img.onload = drawImage;
canvas.width = img.width;
canvas.height = img.height;
ctx.font = "26px Calibri";
$(document).on('input', '#copTitle', function() {
    $('#blankImagediv').css('display', 'block');

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(img, 0, 0);
    ctx.fillStyle = "#0D5F90";
    ctx.fillText($(this).val(), 160, 40);
});
$(document).on('input', '#coupondiscount', function() {
    ctx.fillStyle = "#0D5F90";
    ctx.fillText($(this).val(), 180, 90);
});
function drawImage()
{
   ctx.drawImage(img, 0, 0);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM