[英]How to write text on top of a colored canvas (new to javascript)
Need to put text on top of this canvas. 需要将文本放在此画布的顶部。 I'm sure this has been asked before but I need some help.
我确定之前已经问过,但我需要一些帮助。 Thank you in advance.
先感谢您。
<html>
<body>
<canvas id="myCanvas" width="1280" height="720"
</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="blue";
ctx.fillRect(1,1,2000,2000);
</script>
<script>
car canvas = document.getElementById("myCanvas");
var ctx = canvas.getcontext("2d");
ctx.font = "60px Arial";
ctx.fillText("Text here",200,200);
</script>
</body>
</html>
You have 2 typos: 你有2个拼写错误:
car
instead of var
car
而不是var
And getcontext
instead of getContext
. 和
getcontext
而不是getContext
。
You also need to set fillStyle
, with another color than the background: 您还需要使用另一种颜色而不是背景来设置
fillStyle
:
var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.fillStyle = "blue"; ctx.fillRect(1, 1, 2000, 2000); ctx.fillStyle = "black"; ctx.font = "20px Georgia"; ctx.fillText("Hello World!", 10, 50); ctx.font = "30px Verdana"; ctx.fillText("Big smile!", 10, 90);
<canvas id="myCanvas" width="1280" height="720"> </canvas>
You just need to set a different color to make it visible on your background. 您只需要设置不同的颜色,使其在背景上可见。
For example, add ctx.fillStyle="white";
例如,添加
ctx.fillStyle="white";
before you write the text but after you fill the background. 在您编写文本之前但在填写背景之后。
<html>
<body>
<canvas id="myCanvas" width="300" height="200" style="border:1px solid #d3d3d3 ;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(1, 1, 2000, 2000);
ctx.font = "30px Comic Sans MS";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("Hello World", canvas.width / 2, canvas.height / 2);
</script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.