基于前面写的代码,在gamelets的工程目录下新建一个CanvasAndStage.ts
代码如下
import {Application, Graphics} from 'pixi.js';
// 不要忘了,一定要引用这个css样式,否则就会以默认样式显示
import './style.css'
// app.view就是画布,因为已经指定了泛型:HTMLCanvasElement
let app = new Application<HTMLCanvasElement>();
document.body.appendChild(app.view);
// // 改画布尺寸方法一
// app.renderer.resize(640, 480);
// // 改画布尺寸方法二
// app.view.width = 640;
// app.view.height = 480;
// // app.renderer是渲染器对象
// app.renderer.resize(
// window.innerWidth, // 视窗内部不含框的宽
// window.innerHeight // 视窗内部不含框的高
// )
// app.renderer.render(app.stage);
let stageSize = {
width: 0,
height: 0
}
let stageFrame = new Graphics();
app.stage.addChild(stageFrame);
function refreshCanvasAndStage(): void{
let winSize = {
width: window.innerWidth,
height: window.innerHeight
};
app.renderer.resize(winSize.width, winSize.height);
let scale = Math.min(
winSize.width / stageSize.width,
winSize.height / stageSize.height
);
let stageRealSize = {
width: stageSize.width * scale,
height: stageSize.height * scale
};
app.stage.position.set(
(winSize.width - stageRealSize.width) / 2,
(winSize.height - stageRealSize.height) / 2
);
}
function redrawStageFrame(): void{
stageFrame.clear();
stageFrame.lineStyle({
color: 0xFF0000,
width: 2
})
stageFrame.drawRect(0, 0, stageSize.width, stageSize.height);
}
function setStageSize(width: number, height: number): void{
stageSize.width = width;
stageSize.height = height;
redrawStageFrame();
refreshCanvasAndStage();
}
setStageSize(640, 480);
window.addEventListener('resize', refreshCanvasAndStage);
然后在index.html中,编辑代码,改成如下代码,现在我们引用CanvasAndStage.ts文件,而不要引用main.ts文件。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + TS</title>
</head>
<body>
<div id="app"></div>
<!-- <script type="module" src="/src/main.ts"></script> -->
<script type="module" src="/src/CanvasAndStage.ts"></script>
</body>
</html>
随着浏览器缩放,黑色的画布会跟着缩放,容纳整个浏览器窗口。