class PixiBackground {
constructor(type = 'cover', domElement, imgUrl) {
this.domElement = domElement;
this.imgUrl = imgUrl;
this.parent = new PIXI.Container();
this.sprite = new PIXI.Sprite.fromImage(this.imgUrl);
this.parent.addChild(this.sprite);
this.type = type;
}
addTo(container) {
container.addChild(this.parent);
this.applyResize();
}
applyResize() {
const domSize = {
x: this.domElement.clientWidth,
y: this.domElement.clientHeight
};
const imageSize = {
x: this.sprite.texture.width,
y: this.sprite.texture.height
};
const domElementRatio = domSize.x / domSize.y;
const imageRatio = imageSize.x / imageSize.y;
var scale = 1;
var position = new PIXI.Point(0, 0);
if (this.type == 'cover' ? domElementRatio > imageRatio : domElementRatio < imageRatio) {
scale = domSize.x / imageSize.x;
position.y = -(imageSize.y * scale - domSize.y) / 2;
position.x = 0;
} else {
scale = domSize.y / imageSize.y;
position.x = -(imageSize.x * scale - domSize.x) / 2;
position.y = 0;
}
this.sprite.scale = new PIXI.Point(scale, scale);
this.sprite.position = position;
return this;
}
}
const imgUrl = 'https://images.unsplash.com/photo-1528723624453-3e53a413b392?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ&s=b44ae61a30e1a05f5defbf48cb5956eb';
const canvasParentElement = document.getElementById('canvasParentElement');
const renderer = PIXI.autoDetectRenderer({
width: canvasParentElement.clientWidth,
height: canvasParentElement.clientHeight
});
canvasParentElement.appendChild(renderer.view);
const stage = new PIXI.Container();
const pixiTestObject = new PixiBackground('cover', canvasParentElement, imgUrl);
PIXI.loader.add(imgUrl).load(function() {
pixiTestObject.addTo(stage)
requestAnimationFrame(animate);
function animate() {
requestAnimationFrame(animate);
renderer.render(stage);
}
});
window.addEventListener('resize', debounce(() => onResizeWindow(), 250));
window.addEventListener('resize', debounce(() => pixiTestObject.applyResize(), 250));
function debounce(func, wait, immediate) {
let timeout;
return function() {
let args = arguments;
let later = () => {
timeout = null;
if (!immediate) func.apply(this, args);
};
let callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(this, args);
}
}
function onResizeWindow() {
const canvas = renderer.view;
const w = canvasParentElement.clientWidth;
const h = canvasParentElement.clientHeight;
canvas.style.width = w + 'px';
canvas.style.height = h + 'px';
canvas.width = w;
canvas.height = h;
renderer.resize(w, h);
}
#canvasParentElement {
background: black;
width: 100vw;
height: 100vh;
overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/4.8.1/pixi.min.js"></script>
<div id="canvasParentElement"></div>
window.addEventListener("resize", onResizeHandler)
而不是window.onresize = onResizeHandler
即可。 - Matt