【发布时间】:2021-05-08 16:30:06
【问题描述】:
我正在使用 P5JS 制作蛇游戏。当我开始创建 UI 时,一切都很好,直到我尝试制作一个栏(生活,进步)。为了显示状态,我决定将一定数量的像素复制到渲染纹理。首先,为了检查它是如何工作的,我创建了一个函数。
_cropOverlayTexture() {
let width = this._overlayTexture.width;
let height = this._overlayTexture.height;
this._currentOverlayTexture = createImage(width, height);
this._currentOverlayTexture.loadPixels();
for(let i = 0; i < width; i++) {
for(let j = 0; j < height; j++) {
this._currentOverlayTexture.set(i, j, [20, 250, 0, 255]);
}
}
this._currentOverlayTexture.updatePixels();
}
update() {
if(this._currentStep !== this._oldStep) {
this._cropOverlayTexture();
this._oldStep = this._currentStep;
}
}
draw() {
image(this._barTexture, this._x, this._y, this._width, this._height);
image(this._currentOverlayTexture, this._x, this._y, this._width, this._height);
}
此时,画布内的内容相对于 x 轴发生了偏移。 (画布的尺寸为 800 x 800)
我删除了这部分代码,但缺陷仍然存在。 我尝试改变绘制位置和比例,但它的比例很奇怪,而且图像看起来也很模糊。
function draw() {
background(0);
push();
translate(0, 0);
scale(0.375, 1);
// draw UI
pop();
}
为了比较,这是以前的样子:
我尝试切换到 WEBGL 模式。
function setup() {
createCanvas(CANVAS_SIZE.X, CANVAS_SIZE.Y, WEBGL);
// setup
}
function draw() {
background(0);
push();
translate(-400, -400);
scale(1, 1);
// draw UI
pop();
}
但这并没有帮助。
我也尝试清除浏览器 cookie,重新启动 IDE,计算机,但没有任何帮助。我做错了什么,可能是什么问题?
P.S:例如,我决定删除所有代码并将正方形的显示保留为 100 x 100 像素。
function setup() {
createCanvas(800, 800);
frameRate(30);
}
function draw() {
background(0);
fill("#ff2574");
rect(100, 100, 100, 100);
}
但是图像看起来仍然被拉伸了。
【问题讨论】:
-
这里没有足够的代码来重现您的问题。我在 p5.js 中遇到过模糊的图像,但仅在手动绘制带有像素数组的图像并且没有正确处理像素密度时。最后的代码绝对绘制了一个完全正常的粉红色正方形。如果你没有看到粉红色的形状是正方形,那么我唯一的猜测是画布元素被扭曲了,比如 css 变换或浏览器缩放设置。
-
@PaulWheeler 不幸的是,我不明白为什么会发生这种情况。我创建了一个新项目并运行此代码,我得到了正常的正方形。然后我创建了一个新项目并从游戏项目中复制了所有文件,缺陷出现了。我创建了另一个新项目,重新下载了 P5JS 库并传输了文件的内容。它起作用了,现在一切看起来都像以前一样。
标签: javascript user-interface canvas p5.js