如何使用 JavaScript 和 Canvas 在图像上添加文本 [英] How to add text on image using JavaScript and Canvas

查看:151
本文介绍了如何使用 JavaScript 和 Canvas 在图像上添加文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 JavaScript/jQuery 在现有图像上添加文本.这是我的代码:

<input name="text" id="txt" class="form-control" placeholder="Add Text" type="text" required><div class="col-md-6"><img src="703960808_1011008937_images.png">

</表单>

这里我有一个文本字段.当用户在该文本字段中写一些东西时,它会写在该图像上,并且在提交表单时应该获取编辑过的图像.

解决方案

您只需要使用 canvas.请看我的例子.

var canvas = document.getElementById('canvas'),ctx = canvas.getContext('2d');canvas.width = $('img').width();canvas.crossOrigin = "匿名";canvas.height = $('img').height();ctx.drawImage($('img').get(0), 0, 0);ctx.font = "36pt Verdana";$(document).on('input','#inp',function(){//重绘图像ctx.clearRect(0,0,canvas.width,canvas.height);ctx.drawImage($('img').get(0), 0, 0);//重新填充文本ctx.fillStyle = "红色";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><表格><img style="display:none" src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTsEbEB4kEMHt3WJ13HpZE16hJ3iKrE8ugnErvyln7oNPDma48U" crossorigin="匿名"/><input type="text" id="inp"/><button type="submit">保存</button></表单><canvas id="canvas"/>

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

<form name="billdata" id="billdata"  enctype="multipart/form-data" novalidate>
    <input name="text" id="txt" class="form-control" placeholder="Add Text"  type="text" required>
    <div class="col-md-6">
        <img src="703960808_1011008937_images.png">
    </div>
</form>

Here I have a text field.When user will write something in that text field it will written on that image and the edited image should fetched while form will submit.

解决方案

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" />

这篇关于如何使用 JavaScript 和 Canvas 在图像上添加文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆