此代码用于在图像上写入文本。。我在保存图像时遇到问题,无法将其保存到手机我在这里找到了一个解决方案,并成功地将图片保存到了手机中。。答案1将图像自动保存到本地
但我无法将其用于我的代码
function myFunction() {
document.getElementById("canvas").style.display = "block";
var x = document.getElementById("myText").value;
//demoo document.getElementById("demo").innerHTML = x;
addTextToImage("https://l.top4top.io/p_1549mpaz31.png", x);
}
function addTextToImage(imagePath, text) {
var circle_canvas = document.getElementById("canvas");
var context = circle_canvas.getContext("2d");
// Draw Image function
var img = new Image();
img.src = imagePath;
img.onload = function () {
context.font = "40px Cairo";
context.textAlign = "center";
context.drawImage(img, 0, 0);
context.lineWidth = 1;
context.fillStyle = "#ffffff";
context.lineStyle = "#ffff00";
context.fillText(text, 520, 790);
}
}
@import url('https://fonts.googleapis.com/css?family=Cairo:300,400,600,700,900');
.container {
position: relative;
font-family: Arial;
font-family: 'Cairo';
}
<canvas style="display:none" id="canvas" width="1080" height="1080"></canvas>
<input type="text" id="myText" value="write your name">
<button onclick="myFunction()">button</button> ..
<p id="demoo"></p>
我为您添加了一个代码笔。如果您还有任何疑问,请检查并告诉我。我只是专注于如何从画布下载图像。我认为这是你最关心的问题。
HTML
<input type="text" id="text" placeholder="write your name">
<button onclick="writeText()">Show Image</button>
<button onclick="download()">Download Image</button>
<canvas id="canvas" width="200" height="200"></canvas>
JS
function writeText() {
console.log("Hello")
var canvas = document.getElementById("canvas");
var name = document.getElementById("text").value;
if(name.trim() == "" || name.trim().length == 0) {
alert("Write something in the text box first");
return;
}
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText(name, 10, 50);
}
function download() {
writeText()
var link = document.createElement('a');
link.download = 'text.png';
link.href = document.getElementById("canvas").toDataURL()
link.click();
}
https://codepen.io/kousik-mandal/pen/RwWjmqM
谢谢。