且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript;使用画布在图像上添加文字并保存到图像

更新时间:2023-12-05 16:19:22

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