Javascript 渐变背景上的填充文本不显示

Javascript 渐变背景上的填充文本不显示,javascript,Javascript,当我从strokeText更改为fillText时,文本将消失。我只是有一个渐变画布背景,我试图把填充文本放在渐变上。strokeText工作正常,但当我更改为fillText时,文本就消失了 ''' var canvas = document.getElementById('canvas'); var ctx = canvas.getContext("2d"); var grd = ctx.createRadialGradient(100, 100, 100, 100, 1

当我从strokeText更改为fillText时,文本将消失。我只是有一个渐变画布背景,我试图把填充文本放在渐变上。strokeText工作正常,但当我更改为fillText时,文本就消失了

'''
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
var grd = ctx.createRadialGradient(100, 100, 100, 100, 130, 50);
grd.addColorStop(0, "orange");
grd.addColorStop(1, "yellow");

// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(0, 0, 200, 100);
ctx.font="20px Georgia";
ctx.strokeText("hello",10,30);
'''
HTML


您的浏览器不支持HTML画布标记。

它“消失”,因为您只设置了一次
fillStyle
,因此
fillRect
fillText
都是相同的渐变颜色。文本在那里,但它融入了背景。在文本之前再次更改填充样式


var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
var grd = ctx.createRadialGradient(100, 100, 100, 100, 130, 50);
grd.addColorStop(0, "orange");
grd.addColorStop(1, "yellow");

// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(0, 0, 200, 100);
ctx.fillStyle = "blue";
ctx.font="20px Georgia";
ctx.fillText("hello",10,30);

stroke没有这样做的原因是stroke没有从
fillStyle
获取命令,因此它使用默认值,即黑色。

最好将代码段添加到htmlWelcome堆栈溢出中!寻求代码帮助的问题必须包含在问题中重现问题所需的最短代码,最好是在堆栈片段中。看见

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
var grd = ctx.createRadialGradient(100, 100, 100, 100, 130, 50);
grd.addColorStop(0, "orange");
grd.addColorStop(1, "yellow");

// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(0, 0, 200, 100);
ctx.fillStyle = "blue";
ctx.font="20px Georgia";
ctx.fillText("hello",10,30);