2016-12-14 75 views
0

我需要一个帮助。我无法使用画布和Javascript在画布上绘制多个文本。我在下面解释我的代码。使用画布和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); 
    } 

在这里,我需要的时候用户会写一篇关于第一个输入字段中的文本将写入的图像的顶部,当用户将写在第二个输入字段中的文本,将写在不同地方的图​​像,但第一文字不应该取代。在这里,我的问题是每个文本都替换别人。请帮助我。

+0

在渲染第二个文本之前不要清除画布。从第二个函数中删除'ctx.clearRect(0,0,canvas.width,canvas.height)'和'ctx.drawImage(img,0,0);'将它们放在文本顶部第一个功能。 – Blindman67

+0

@ManojLodhi在这里一直发生,没有什么可担心的,只要OP的问题解决了,一切都很好。 :) – Blindman67

回答

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); 
}