This commit is contained in:
2019-01-08 23:49:27 -08:00
parent d479c2caef
commit 7481d23389
2 changed files with 22 additions and 15 deletions

View File

@@ -14,7 +14,8 @@ export interface State {
}
interface SrcSetInfo {
srcSet: string;
jpeg: string;
webp: string;
bestSrc: string;
}
@@ -44,17 +45,21 @@ export class Picture extends React.PureComponent<Props, State> {
const srcSet = this._srcset();
return (
<img
onClick={this.props.onClick}
srcSet={srcSet.srcSet}
src={srcSet.bestSrc}
width={this.props.width + "px"}
/>
<picture>
<source srcSet={srcSet.webp} type="image/webp" />
<source srcSet={srcSet.jpeg} type="image/jpeg" />
<img
onClick={this.props.onClick}
src={srcSet.bestSrc}
width={this.props.width + "px"}
/>
</picture>
);
}
private _srcset = (): SrcSetInfo => {
const srcs: string[] = [];
const jpegSrcSet: string[] = [];
const webpSrcSet: string[] = [];
let bestSize = 1600;
let bestRatio = Infinity;
@@ -67,7 +72,10 @@ export class Picture extends React.PureComponent<Props, State> {
const scale = width / this.props.width;
if (scale >= 1) {
srcs.push(`img/${size}/${this.props.image.src} ${scale}x`);
const jpeg = `img/${size}/${this.props.image.src}`;
const webp = jpeg.replace("jpg", "webp");
jpegSrcSet.push(`${jpeg} ${scale}x`);
webpSrcSet.push(`${webp} ${scale}x`);
if (scale < bestRatio) {
bestSize = size;
bestRatio = scale;
@@ -75,10 +83,9 @@ export class Picture extends React.PureComponent<Props, State> {
}
});
srcs.push(`img/${bestSize}/${this.props.image.src} 1x`);
return {
srcSet: srcs.join(","),
jpeg: jpegSrcSet.join(","),
webp: webpSrcSet.join(","),
bestSrc: `img/${bestSize}/${this.props.image.src}`
};
};