如标题中所述,我希望能够使用按钮onclick功能将文本框中的文本插入画布内。现在请记住我是一个新手,因此可能会出现错误。
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>
答案 0 :(得分:0)
@ 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>
答案 1 :(得分:0)
从我的角度来看,最好将方法直接存储在您的对象check (keyword in ('a', 'b', 'c' .......))
下。该方法可以直接调用,您只需要myGameArea
,然后get 2D context of canvas
。
必填代码示例,完整代码如下:
fill it
<button onclick="myGameArea.myFunction()">Submit</button>
var myGameArea = {
...
myFunction : function() {
var txt=document.getElementById("Box");
var ctx=this.canvas.getContext("2d");
ctx.font="20px Georgia";
ctx.fillText(txt.value, 10, 20);
}
}
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]);
},
myFunction : function() {
var txt=document.getElementById("Box");
var ctx=this.canvas.getContext("2d");
ctx.font="20px Georgia";
ctx.fillText(txt.value, 10, 20);
}
}
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}