首页 > 解决方案 > html5画布没有输出文本怎么办?

问题描述

<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”。文字不打印怎么办?

标签: javascripthtml5-canvas

解决方案


你需要纠正两件事:

  • numText替换函数this中对的引用。当您调用该函数时,您会在特定实例的上下文中执行此操作,并使用关键字来引用其属性writeText
    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();

推荐阅读