通过在Javascript中获取用户输入将文本替换为图像?

时间:2016-01-06 05:56:25

标签: javascript html css

我必须修改此程序以用文本替换图像。在此程序中,输入框的值应反映在气球图像的位置。你能帮帮我吗?

计划链接:

$('#draw').click(function() {
    var text = document.getElementById('txtBallon').value;

        var $ballon = $('#ballon'),
            $canvas = $('#canvas');
        var ballon_x = $ballon.offset().left - $canvas.offset().left,
            ballon_y = $ballon.offset().top - $canvas.offset().top;

        context.drawImage(ballon, ballon_x, ballon_y);

        $ballon.hide();
        $(this).attr('disabled', 'disabled');
    });

JSFiddle

2 个答案:

答案 0 :(得分:1)

你可以这样做:

context.font = "30px Verdana";
context.fillText(text,ballon_x,ballon_y);

而不是context.drawImage(ballon, ballon_x, ballon_y);

<强> Working Fiddle

<强> Updated Fiddle with text drag

答案 1 :(得分:1)

我就是这样做的:

$(document).ready(function() {
  var d_canvas = document.getElementById('canvas');
  var context = d_canvas.getContext('2d');
  var background = document.getElementById('background');
  context.drawImage(background, 0, 0);

  $('.drag').draggable();

  $('#draw').click(function() {
      var $canvas = $('#canvas');

var textX = $('#myText').offset().left - $canvas.offset().left;
var textY = $('#myText').offset().top - $canvas.offset().top + 12;
        context.font= "13px Arial";
        context.fillText($("#myText").text(),textX,textY);

        $('#myText').hide();
    $(this).attr('disabled', 'disabled');
  });
});

$("#theText").keyup(function(){
    $("#myText").text($(this).val());
});

Here is the updated JSFiddle demo