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

标签 javascript html css buttonclick

如标题中所述,我希望能够使用按钮的 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/

相关文章:

javascript - 使用 JavaScript 和 jQuery 进行表格排序的问题

c# - AJAX + ASP.net 从 Sql Server 检索数据?

css - 添加 <nav> 或任何内容会使我的背景图片和我的 div 的内容消失

javascript - 在 Canvas 中创建形状时减少 ctx 的使用

html - 如何使用html和css使文本位于图像的右侧

html - 中间有图像的水平线的CSS技术

html - 以页眉为中心的垂直边框/分隔线

html - 在父鼠标悬停时更改子样式,使用 :after

javascript - 将文本放在 p5.js 中的草图之上

javascript - 如何将事件绑定(bind)到此的 jQuery .live() 转换为 .on()?