【发布时间】:2020-03-28 11:19:10
【问题描述】:
我正在使用画布绘制简单的矩形并用地板图案 (PNG) 填充它们。但是,如果我使用“相机”脚本来处理 HTML5 画布的变换偏移,矩形形状会适当移动,但填充图案似乎总是从屏幕上的固定点绘制(我假设是左上角)。有没有办法“确定”填充图案,使其始终与矩形对齐,无论画布变换,还是在 fill() 上添加可以在代码中其他地方计算的偏移量的方法?我当然可以只使用 drawImage(),但绘制矩形对我的目的来说更通用。
sampleDrawFunction(fillTexture, x1, y1, x2, y2) {
// This is oversimplified, but best I can do with a ~10k lines of code
x1 -= Camera.posX;
x2 -= Camera.posX;
y1 = -1 * y1 - Camera.posY;
y2 = -1 * y2 - Camera.posY;
// Coordinates need to be adjusted for where the camera is positioned
var img = new Image();
img.src = fillTexture;
var pattern = this.ctx.createPattern(img, "repeat");
this.ctx.fillStyle = pattern;
// Translate canvas's coordinate pattern to match what the camera sees
this.ctx.save();
this.ctx.translate(Camera.posX - Camera.topLeftX, Camera.posY - Camera.topLeftY);
this.ctx.fillStyle = pattern;
this.ctx.fillRect(x1, y1, x2 - x1, y2 - y1);
this.ctx.restore();
}
谢谢。
【问题讨论】:
-
一旦你在画布上画了一些东西,它就变成了像素。绘制完所有内容后应用变换不应最终给出您观察到的结果。你确定你做事的顺序是正确的吗?有没有办法提供minimal, reproducible example?
-
我没提,刷新60帧,每帧重绘。每个绘制的项目都会应用变换。
标签: javascript html canvas