draw-image-fit.js 1.5 KB

12345678910111213141516171819202122232425
  1. import { calculateConcreteRect } from "../../utils/object-sizing";
  2. import uni from "../../utils/global";
  3. export default {
  4. name: 'drawImageFit',
  5. handle: async (canvas, ctx, url, options) => {
  6. var _a, _b, _c;
  7. const [error, imageInfo] = await uni.getImageInfo({ src: url });
  8. // 配置默认值
  9. const style = Object.assign({ radius: 0, objectFit: 'cover', intrinsicSize: { width: (_a = imageInfo === null || imageInfo === void 0 ? void 0 : imageInfo.width) !== null && _a !== void 0 ? _a : 100, height: (_b = imageInfo === null || imageInfo === void 0 ? void 0 : imageInfo.height) !== null && _b !== void 0 ? _b : 100 }, specifiedSize: { width: 100, height: 100 }, intrinsicPosition: ['center', 'center'], specifiedPosition: [0, 0] }, options);
  10. // 计算图片尺寸
  11. const drawImageInfo = calculateConcreteRect(style, style.intrinsicSize, style.specifiedSize);
  12. // 如有圆角, 则进行裁剪
  13. if (style.radius > 0) {
  14. ctx.save();
  15. (_c = ctx.setFillStyle) === null || _c === void 0 ? void 0 : _c.call(ctx, 'transparent');
  16. ctx.fillStyle = 'transparent';
  17. ctx.fillRoundRect(style.specifiedPosition[0], style.specifiedPosition[1], style.specifiedSize.width, style.specifiedSize.height, style.radius);
  18. ctx.clip();
  19. }
  20. const result = await ctx.drawImage(url, ...Object.values(drawImageInfo));
  21. if (style.radius > 0)
  22. ctx.restore();
  23. return result;
  24. }
  25. };