我想在渐变上写一些文字(制作比例):
到目前为止,我有这个:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create gradient
var grd = ctx.createLinearGradient(0,0,500,0);
grd.addColorStop(0,"red");
grd.addColorStop(0.5,"yellow");
grd.addColorStop(1,"green");
// Fill with gradient
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);
ctx.fillStyle = grd;
ctx.fillRect(0,0,500,100);
<canvas id="myCanvas" width="500" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
我看不到文字。我该如何解决这个问题?
从我给出的某个分数生成圆圈。
答案 0 :(得分:1)
有两个问题:
在矩形之后移动文本绘图,并更改其颜色:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create gradient
var grd = ctx.createLinearGradient(0,0,500,0);
grd.addColorStop(0,"red");
grd.addColorStop(0.5,"yellow");
grd.addColorStop(1,"green");
// Fill with gradient
ctx.font = "30px Arial";
ctx.fillStyle = grd;
ctx.fillRect(0,0,500,100);
ctx.fillStyle = "#000";
ctx.fillText("Hello World",10,50);
<canvas id="myCanvas" width="500" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
答案 1 :(得分:0)
您可能希望最后设置文本。我可以看到你正在绘制已经绘制的文本上的填充矩形。试着这样做:
<canvas id="myCanvas" width="500" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create gradient
var grd = ctx.createLinearGradient(0,0,500,0);
grd.addColorStop(0,"red");
grd.addColorStop(0.5,"yellow");
grd.addColorStop(1,"green");
// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(0,0,500,100);
//write text with canvas methods
c.fillStyle = '#000000';
c.font = "30px Arial";
c.fillText("Hello World",10,50);
</script>
您可能还需要考虑查找canvas.textAlign
和canvas.textBaseline
属性来定位文字;