簡體   English   中英

文字未顯示在HTML5中的畫布上

[英]Text not showing on canvas in HTML5

我正在嘗試在屏幕上顯示文本,但對我來說不起作用。

這是我的一些代碼,可讓您了解我的所作所為:

duck.js

class duck {
  constructor (canvas, logs = false, start = () => {}, update = () => {}) {
    document.documentElement.style.overflowX = 'hidden';

    self.canvas = canvas;
    self.ctx = self.canvas.getContext('2d');
    self.logs = logs;

    self.keys = {};
    window.onkeyup = (e) => self.keys[e.keyCode] = false;

    var dpi = window.devicePixelRatio;
    var style_height = +getComputedStyle(self.canvas).getPropertyValue("height").slice(0, -2);
    var style_width = +getComputedStyle(self.canvas).getPropertyValue("width").slice(0, -2);
    self.canvas.setAttribute('height', style_height * dpi);
    self.canvas.setAttribute('width', style_width * dpi);

    self.init = () => {
        var a;

        self.logs ? console.info('Duck initialized!') : a = 0;
    };

    self.init.call();

    start();
    setInterval(update, 1);
  };

  rect (x = 0, y = 0, w = 1, h = 1, color = "#FFFFFF", fill = true) {
    self.ctx.fillStyle = color;
    fill ? self.ctx.fillRect(x, y, w, h): self.ctx.strokeRect(x, y, w, h);
  }

  fill (color = "#000000") {
    self.ctx.fillStyle = color;
    self.ctx.fillRect(0, 0, canvas.width, canvas.height);
  }

  text (x = 0, y = 0, text = 'Hello world!', align='left', font = '16px Verdana', color = '#000000') {
    self.ctx.font = font;
    console.log(self.ctx.font)
    self.ctx.fillStyle = color;
    console.log(self.ctx.fillStyle);
    self.ctx.textAlign = align;
    console.log(self.ctx.textAlign)
    self.ctx.fillText(text, x, y);
  }

  get getWidth() {
    return canvas.width;
  }

  get getHeight() {
    return canvas.height;
  }

  screenshot() {
    var image = self.canvas.toDataURL('image/png').replace("image/png", "image/octet-stream");
    window.location.href = image;
  }

  keyDown(key = 'q') {
    if (self.keys[key]) {return true} else {return false};
  }
}

index.js

let duck_core = new duck(document.getElementById('main'), true, start, update);

function start() {
  console.log('test');
}

function update() {
  duck_core.fill('#FFFFFF');
  duck_core.rect(0, 0, duck_core.getWidth, 10, '#222222');
  duck_core.text(0, 0);

  if (duck_core.keyDown('q')) {
    duck_core.screenshot();
  }
}

之所以沒有顯示,是因為該文本的中心點位於左下角而不是右上角。 為了解決這個問題,我在y位置添加了文本大小,在本例中為16px。

改變self ,以this你里面duck類。 在JavaScript中,全局self變量是對window對象的引用,這意味着它不指向類的實例:

MDN

編輯

您還必須更新以下部分:

get getWidth() {
    return this.canvas.width; // added "this"
}

get getHeight() {
    return this.canvas.height; // added "this"
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM