html5canvas没有输出文本怎么办?

What should I do if text is not output from html5 canvas?

<script>
    var canvas = document.getElementById('canvas'),
    context = canvas.getContext('2d');

    function numText(num,x,y) 
    {
    this.num = num,
    this.x = x,
    this.y = y;
    }

    numText.prototype.writeText = function()
    {
    context.font ='60px Bahnschrift SemiCondensed';
    context.fillStyle = 'red';
    context.fillText(numText.text,numText.x,numText.y);
    }

    var text1 = new numText("30",100,225);
    text1.writeText();
</script>

我想用面向对象编程的概念打印出“30”。 文字打印不出来怎么办?

您需要更正两件事:

  • writeText 函数中将对 numText 的引用替换为 this
    当您调用该函数时,您是在特定实例的上下文中执行的并使用 this 关键字来引用其属性
  • 当调用 context.fillText 时,您使用 属性 text 而不是 num 作为第一个参数

更正后的代码:

var canvas = document.getElementById('canvas'),
    context = canvas.getContext('2d');

function numText(num, x, y) {
    this.num = num,
        this.x = x,
        this.y = y;
}

numText.prototype.writeText = function () {
    context.font = '60px Bahnschrift SemiCondensed';
    context.fillStyle = 'red';
    context.fillText(this.num, this.x, this.y);
}

var text1 = new numText("30", 100, 225);
text1.writeText();