How to add text on image using JavaScript and Canvas

前端 未结 1 1701
我在风中等你
我在风中等你 2020-12-05 03:33

I need to add text on existing image using JavaScript/jQuery. Here is my code:

相关标签:
1条回答
  • 2020-12-05 04:21

    All you need is to use canvas. Please take a look at my example.

    var canvas = document.getElementById('canvas'),
            ctx = canvas.getContext('2d');
    canvas.width = $('img').width();
    canvas.crossOrigin = "Anonymous";
    canvas.height = $('img').height();
    ctx.drawImage($('img').get(0), 0, 0);
    ctx.font = "36pt Verdana";
    $(document).on('input','#inp',function(){
        //redraw image
        ctx.clearRect(0,0,canvas.width,canvas.height);
        ctx.drawImage($('img').get(0), 0, 0);
        //refill text
        ctx.fillStyle = "red";
        ctx.fillText($(this).val(),40,80);
    });
    $('button').click(function(){
        console.log(ctx.getImageData(50, 50, 100, 100));
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form>
        <img style="display:none" src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTsEbEB4kEMHt3WJ13HpZE16hJ3iKrE8ugnErvyln7oNPDma48U" crossorigin="anonymous"/>
     <input type="text" id="inp"/>
      <button type="submit">Save</button>
    </form>
    
    <canvas id="canvas" />

    0 讨论(0)
提交回复
热议问题