gpt4 book ai didi

javascript - HTML5 中的文本未显示在 Canvas 上

转载 作者:行者123 更新时间:2023-12-02 23:48:16 25 4
gpt4 key购买 nike

我正在尝试在屏幕上显示文本,但它不适合我。

这是我的一些代码,您可以了解我所做的事情:

鸭子.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。

关于javascript - HTML5 中的文本未显示在 Canvas 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55749123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com