gpt4 book ai didi

javascript - 如何使用按钮 onclick 函数将文本插入 Canvas 内?

转载 作者:行者123 更新时间:2023-11-28 01:40:44 26 4
gpt4 key购买 nike

如标题中所述,我希望能够使用按钮的 onclick 函数将文本从文本框插入到 Canvas 内部。请记住,我是这方面的新手,所以可能到处都是错误。

function startGame() {
myGameArea.start();
}

var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
this.gravity = 0.05;
this.gravitySpeed = 0;
document.body.insertBefore(this.canvas, document.body.childNodes[0]);

}
}

function myFunction() {

}
canvas { 
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
<body onload="startGame()">
<input type="text" name="Box" id="Box" value="" placeholder="Write whatever"/>
<button onclick="myFunction()">Submit</button>
</body>

最佳答案

@sosa123,检查下面的解决方案,让我知道这个解决方案是否适合你?

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>
function startGame() {
myGameArea.start();
}

var myGameArea = {
canvas : createElementOnDom('CANVAS','myCANVAS'),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
this.gravity = 0.05;
this.gravitySpeed = 0;
document.body.insertBefore(this.canvas,document.body.childNodes[0]);

}
}

function createElementOnDom (type,id) {
var element=document.createElement(type);
element.id=id;
return element;
}
function myFunction() {
var canvas = document.getElementById("myCANVAS");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText(document.getElementById("Box").value,10,50);
}
</script>
<style>
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body>
<body onload="startGame()">
<input type="text" name="Box" id="Box" value="" placeholder="Write whatever"/>
<button onclick="myFunction()">Submit</button>
</body>
</body>
</html>

关于javascript - 如何使用按钮 onclick 函数将文本插入 Canvas 内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50445474/

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