gpt4 book ai didi

javascript - 使用 Canvas 将文本添加到图像

转载 作者:行者123 更新时间:2023-11-28 18:44:41 25 4
gpt4 key购买 nike

我想创建一个小网站,以便在图像上添加文本。我添加了一个文本框和一个按钮来插入自定义文本,但它不起作用。我究竟做错了什么?提前致谢

<script>

function = function1(){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var imageObj = new Image();

t = document.getElementById('text').value;

if(t == '' || t == null) {
word = "you forgot to put something";
} else {
word = t;
}

};

imageObj.onload = function(){
context.drawImage(imageObj, 10, 10);
context.font = "40pt Calibri";
context.fillText(word, 20, 20);
};
imageObj.src = "img/image.jpg";
};


</script>

<body>
<canvas id="myCanvas" width="578" height="400"></canvas>
</body>

<form>
Text: <input id="textBox" placeholder="your text"/>
<br>
<input type='submit' id="submit" value="submit" onClick="function1()" >
</form>

最佳答案

通过查看您的代码,您似乎正在尝试在加载图像之前绘制文本。

您必须首先调用window.onload函数。

来自 MDN

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.

这是一个小例子。

window.onload = function(){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function(){
context.drawImage(imageObj, 10, 10);
context.font = "40pt Calibri";
context.fillText("My TEXT!", 50, 50);
};
imageObj.src = "http://cdn.playbuzz.com/cdn/503aeb8a-c1b8-4679-8ed3-da5e11643f29/8a940ebd-8630-4247-888e-c4c611f4f0e2.jpg";
};
<canvas id="myCanvas"></canvas>

关于javascript - 使用 Canvas 将文本添加到图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35563348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com