分割雪碧图

662 阅读1分钟

json中需要携带每张图片的位置信息 通过.then接受

        async createImg(path = "地址") {
            let source = [
                {
                    url: path + ".png",
                    type: "file",
                },
                {
                    url: path + ".json",
                    type: "json",
                },
            ];
            function queryFile(params) {
                return new Promise((resolve) => {
                    fetch(params.url, { method: "GET" })
                        .then((res) => {
                            if (params.type == "file") return res.blob();
                            if (params.type == "json") return res.json();
                        })
                        .then((res) => {
                            if (params.type == "file") {
                                let file = new FileReader();
                                file.readAsDataURL(res);
                                file.onload = (e) => {
                                    let img = new Image();
                                    img.src = e.target.result;
                                    img.onload = () => {
                                        resolve(img);
                                    };
                                };
                            }
                            if (params.type == "json") resolve(res);
                        })
                        .catch((error) => {
                            console.log(error);
                        });
                });
            }
            let arr = [];
            for (let i = 0; i < source.length; i++) {
                arr.push(queryFile(source[i]));
            }
            let result = {};
            let list = await Promise.all(arr);
            let [img, json] = list;
            for (let key in json) {
                let { x, y, width, height } = json[key];
                let canvas = document.createElement("canvas");
                canvas.width = width;
                canvas.height = height;
                let context = canvas.getContext("2d");
                context.drawImage(
                    img,
                    x,
                    y,
                    width,
                    height,
                    0,
                    0,
                    width,
                    height
                );
                result[key] = {
                    ...json[key],
                    url: canvas.toDataURL(),
                };
            }
            return result;
        },