HTML5 - 画布:在渐变上绘制文本

时间:2016-01-12 22:09:56

标签: javascript css html5 canvas

我想在渐变上写一些文字(制作比例):

到目前为止,我有这个:

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>

我看不到文字。我该如何解决这个问题?

我想创建这个: enter image description here

从我给出的某个分数生成圆圈。

2 个答案:

答案 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.textAligncanvas.textBaseline属性来定位文字;