1添加css样式识别
在 var CSSParsedDeclaration = /** @class */ (function () { 之前添加代码
var objectFit = {
name: 'object-fit',
initialValue: 'fill',
prefix: false,
type: 2 /* IDENT_VALUE */,
parse: function (_context, overflow) {
switch (overflow) {
case 'none':
return "none"
case 'contain':
return "contain"
case 'cover':
return "cover"
case 'fill':
default:
return "fill";
}
}
};
2.在 var CSSParsedDeclaration = /** @class */ (function () { 中
this.marginLeft = parse(context, marginLeft, declaration.marginLeft);后面加入
this.objectFit = parse(context, objectFit, declaration.objectFit);
3.在Cache.prototype.addImage = function (src,cssStyle) 。。修改为
Cache.prototype.addImage = function (src,cssStyle) {
var result = Promise.resolve();
if (this.has(src)) {
return result;
}
if (isBlobImage(src) || isRenderable(src)) {
(this._cache[src] = this.loadImage(src,cssStyle)).then(res=>{
if(cssStyle && cssStyle instanceof CSSStyleDeclaration ){
res.style = cssStyle.cssText;
}
}).catch(function () {
// prevent unhandled rejection
});
return result;
}
return result;
};
4.修改var ImageElementContainer = /** @class */ (function (_super) {中
_this.context.cache.addImage(_this.src,img.style);
5.修改 CanvasRenderer.prototype.renderReplacedElement = function (container, curves, image)
CanvasRenderer.prototype.renderReplacedElement = function (container, curves, image) {
if (image && container.intrinsicWidth > 0 && container.intrinsicHeight > 0) {
var box = contentBox(container);
var path = calculatePaddingBoxPath(curves);
this.path(path);
this.ctx.save();
this.ctx.clip();
let type = image.style.objectFit;
let radio = 1, // 容器与图片的比例
sx = 0, // 开始剪切的 x 坐标位置。
sy = 0, // 开始剪切的 y 坐标位置。
swidth = container.intrinsicWidth, // 被剪切图像的宽度。
sheight = container.intrinsicHeight, // 被剪切图像的高度。
x = box.left, // 在画布上放置图像的 x 坐标位置。
y = box.top, // 在画布上放置图像的 y 坐标位置。
width = box.width, // 要使用的图像的宽度(伸展或缩小图像)。
height = box.height; // 要使用的图像的高度(伸展或缩小图像)。
let cWHRatio = width / height;
let iWHRatio = swidth / sheight;
if (type === "cover") {
// cover模式,需要裁剪
if (iWHRatio >= cWHRatio) {
// 横图,高先匹配,裁剪宽度
radio = height / sheight;
sx = (swidth - width / radio) / 2;
swidth = width / radio;
} else {
// 竖图,宽先匹配,裁剪高度
radio = width / swidth;
sy = (sheight - height / radio) / 2;
sheight = height / radio;
}
} else if (type === "contain") {
if (iWHRatio >= cWHRatio) {
// 横图,宽先匹配,高度自适应
radio = width / swidth;
y += (height - sheight * radio) / 2;
height = sheight * radio;
} else {
// 竖图,高先匹配,宽度自适应
radio = height / sheight;
x += (width - swidth * radio) / 2;
width = swidth * radio;
}
} else if (type === "none") {
if(swidth >= width){
// 图宽大于区域宽
sx += (swidth - width) /2
swidth = width;
}else{
x += (width - swidth ) /2
width = swidth;
}
if(sheight >= height){
// 图高大于区域高
sy += (sheight - height) /2
sheight = height;
}else{
y += (height - sheight ) /2
height = sheight;
}
}
this.ctx.drawImage(image,sx,sy,swidth,sheight,x,y,width,height);
this.ctx.restore();
}