2016-01-12 150 views
-2

我想寫通過梯度一些文字(做一個刻度):HTML5 - 畫布:繪製文本在梯度

我有這個至今:

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

回答

0

這裏有兩個問題:

  • 你繪製上層建築文本
  • 您正在繪製在同一個漸變的背景和文本的背景,所以文字會出現在頂無形背景

移動文本,繪圖後的矩形,並改變其顏色:

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>

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性能;