Javascript;使用画布在图像上添加文字并保存到图像 [英] Javascript; Adding text on image using canvas and save to image
本文介绍了Javascript;使用画布在图像上添加文字并保存到图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只想创建一个页面,您可以在其中输入文字并将其添加到所选图片上,并将其另存为新图片。
i just want to make a page where u can type a text and add it on selected image and save that as new image.
我试图做几个方法,但没有运气。
I tried to do it in few ways, but without luck.
<body>
<canvas id = "idCanvas" width = "576" height = "577"> </canvas>
<img id="canvasImg" width = "576" height = "577"></img>
<script>
window.onload = function(){
var canvas = document.getElementById('idCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
var dataURL = canvas.toDataURL();
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0, 576, 577);
context.font = "20px Calibri";
context.fillText("My TEXT!", 50, 200);
document.getElementById('canvasImg').src = toDataURL();
window.alert(dataURL);
};
imageObj.src = "image.png";
};
</script>
当我使用toDataURL在img src中,图像将不会显示,它只有在我不在canvas中使用drawImage时才有效。
When i use toDataURL() in img src, the image won't be displayed, it only works if i'm not using drawImage in canvas.
推荐答案
Ok所以是它不会工作的安全原因,但有一个解决方案。
查看此处的工作演示: FIDDLE
Ok so yes it will not work for security reason, but there is a solution. See here a working demo: FIDDLE
draw();
function draw() {
var canvas = document.getElementById('idCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
context.font = "40px Calibri";
context.fillStyle = "red";
context.fillText("My TEXT!", 50, 300);
var canvas = document.getElementById('idCanvas');
var dataURL = canvas.toDataURL();
alert(dataURL);
}
imageObj.setAttribute('crossOrigin', 'anonymous');
imageObj.src = "http://lorempixel.com/400/200/";
};
这篇关于Javascript;使用画布在图像上添加文字并保存到图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文