使用psd.js中遇到的问题总结

项目需要将设计师做好的psd文件解析为格式化的主体和模板数据,最终我们选用psd.js来做psd文件解析,成功入坑,开发过程异常痛苦,官方文档比较简洁,使用的人少,而且github上很早有人提的Issue到现在为止很多要么完全没回复,要么未解决,而这些问题恰恰是我们开发过程中需要解决的痛点,一路摸着石头过河,现将总结的一些问题的解决方案记录下来,希望对同样入坑psd.js的朋友有所帮助。

以下问题大都针对文本图层信息的解析,在开始之前我们需要找到文本图层,以及获取一些图层的元信息,这里假设我们的文本图层的索引为0。

const root = psd.tree();
const textLayer = root.children()[0];
const typeTool = textLayer.get('typeTool');
const { transform, font, value } = textLayer.export();

1、获取文本图层的内容

const text = value

2、精确获取文本 图层 的位置信息

const { textData } = typeTool;
const { bounds } = textData;
const { xx, tx, yy, ty } = transform;
const [ positionTop, positionLeft, positionRight, positionBottom ] = ['Top ', 'Left', 'Rght', 'Btom'].map(key => bounds[key].value);
const x = tx * xx + positionLeft ;
const y = ty * yy + positionTop;

3、精确获取文本 图层 的宽高信息

const { textData } = typeTool;
const { bounds } = textData;
const { xx, tx, yy, ty } = transform;
const [ positionTop, positionLeft, positionRight, positionBottom ] = ['Top ', 'Left', 'Rght', 'Btom'].map(key => bounds[key].value);
const width = (positionRight - positionLeft) * xx;
const height = (positionBottom - positionTop) * yy;

4、获取文本图层文本的对其方式(数组第一个为水平对其方式,第二个为垂直对其方式)

const [textAlign = 'left', textVAlign = 'top'] = font.alignment || [];

5、获取文本图层文本的字体(这里目前只支持单字体)

const fontFamily = (font.name || '').replace(/\s|\0/g, '');

6、获取文本图层文本的颜色(这里目前只支持单颜色)

function rgbToHex([r, g, b]) {
    const bin = (r << 16 | g << 8 | b).toString(16);
    return `#${bin.padStart(6, '0')}`;
}

const fontColor = font.colors && font.colors.length ? rgbToHex(font.colors[0]) : '#000000';

7、获取文本图层文本的字体大小

const { yy } = transform;
const fontSize = Math.round(font.sizes[0]* yy)

8、获取文本图层文本的行高

const { Leading } = typeTool.styles();
const lineHeight =  Leading && !isNaN(Number(Leading[0])) ? fontSize + Leading[0] / 2 :  fontSize * 1.2;

9、获取文本图层文本的字间距

const { Tracking } = typeTool.styles();
const letterSpacing = Tracking ? Math.round(Tracking[0] * fontSize / 1000) : 0;

10、获取文本图层的旋转角度(不要尝试去获取图片图层的旋转角度,纯粹浪费时间,ps应用旋转后就山哥了图层,获取不到的)

function getRotation(transform) {
    let rotation = Math.round(Math.atan(transform.xy / transform.xx) * (180 / Math.PI));
    if (transform.xx < 0) {
        rotation += 180;
    } else if (rotation < 0) {
        rotation += 360;
    }
    return rotation;
}

const rotation = getRotation(transform);

如果有其他psd.js相关疑难问题的解决方案,也请大家多多指教。

  • 支付宝二维码 支付宝
  • 微信二维码 微信

本文地址: /psd-js-common-cases.html

版权声明: 本文为原创文章,版权归 逐梦个人博客 所有,欢迎分享本文,转载请保留出处!

相关文章