aboutsummaryrefslogtreecommitdiffstats
path: root/packages/website/ts/@next/components/image_loop.tsx
blob: 2dc6c7aeed1cd347a01efe68a19d82a50735c1d6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import * as React from 'react';
import * as _ from 'lodash/collection';
import styled from 'styled-components';

interface Props {
    name: string;
    size?: 'small' | 'medium' | 'large' | number;
}

export class ImageLoop extends React.Component<Props> {
    private _img: Image;
    private _ctx: CanvasRenderingContext2D;
    private _x = 0;
    private _speed = -1;
    private _canvas = React.createRef();

    constructor(props: Props) {
        super(props);
    }
    public componentDidMount(): void {
        const domImage = React.Children.only(this.props.children);

        this._img = new Image(1446, 407);
        this._img.src = domImage.props.src;
        this._ctx = this._canvas.current.getContext('2d');

        this._img.onload = this.updateCanvas.bind(this);
    }
    public render(): React.ReactNode {
        return (
            <Wrapper {...this.props}>
                <canvas id="canvas" style={{ width: '100vw', height: '407px' }} ref={this._canvas} />
            </Wrapper>
        );
    }
    public updateCanvas(): void {
        this.move();

        const { width, height } = this._canvas.current;

        this._ctx.clearRect(0, 0, width, height);
        this.draw();

        requestAnimationFrame(this.updateCanvas.bind(this));
    }
    public move(): void {
        this._x += this._speed;
        this._x %= this._canvas.current.width;
    }
    public draw(): void {
        const img = this._img;
        const imgWidth = img.naturalWidth / 2;
        const imgHeight = img.naturalHeight / 2;
        const currentPosition = this._x;
        const canvasWidth = this._canvas.current.width;

        this._ctx.drawImage(img, currentPosition, 0, imgWidth, imgHeight);

        if (this._speed < 0) {
            this._ctx.drawImage(img, currentPosition + canvasWidth, 0, imgWidth, imgHeight);
        } else {
            this._ctx.drawImage(img, currentPosition - imgWidth, 0, imgWidth, imgHeight);
        }
    }
}

export const Wrapper = styled.div`
    margin: 0 0;
    display: flex;
    align-items: center;
    justify-content: center;
`;