更新周边功能
This commit is contained in:
@@ -1,10 +1,10 @@
|
||||
export default class Haibao {
|
||||
constructor(width, height, color = '#fff') {
|
||||
this.canvas = document.createElement('canvas');
|
||||
this.ctx = this.canvas.getContext('2d', { alpha: false });
|
||||
this.ctx = this.canvas.getContext('2d', { alpha: true });
|
||||
this.canvas.width = width;
|
||||
this.canvas.height = height;
|
||||
this.ctx.fillStyle = color;
|
||||
// this.ctx.fillStyle = color;
|
||||
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height)
|
||||
|
||||
this.zIndex = 0
|
||||
@@ -29,26 +29,50 @@ export default class Haibao {
|
||||
this.imagePromises.push(loadPromise);
|
||||
return loadPromise;
|
||||
}
|
||||
text (text, x, y, opts) {
|
||||
const { font = '16px sans-serif', color = '#000', align = 'center' } = opts || {};
|
||||
this.ctx.font = font;
|
||||
this.ctx.fillStyle = color;
|
||||
|
||||
const drawText = (text, x, y) => {
|
||||
this.ctx.fillText(text, x, y);
|
||||
};
|
||||
const totalWidth = this.ctx.measureText(text).width;
|
||||
|
||||
if (align === 'center') {
|
||||
x -= totalWidth / 2;
|
||||
}
|
||||
|
||||
drawText(text, x, y);
|
||||
|
||||
return this
|
||||
}
|
||||
async draw (mask = 'source-over') {
|
||||
await Promise.all(this.imagePromises);
|
||||
|
||||
// 绘制所有图片
|
||||
this.images.sort((a, b) => a.zIndex - b.zIndex)
|
||||
this.images.forEach(({ img, x, y, zIndex }, idx) => {
|
||||
this.ctx.drawImage(img, x, y);
|
||||
if (idx === 0) {
|
||||
this.ctx.globalCompositeOperation = mask
|
||||
} else {
|
||||
this.ctx.globalCompositeOperation = 'source-over'
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* 生成合成后的图片(返回Promise)
|
||||
* @returns {Promise<string>} 合成后的Base64图片数据
|
||||
*/
|
||||
async generate (mimeType = 'image/jpeg', quality = .8) {
|
||||
async generate ({ mimeType = 'image/jpeg', quality = .8 }) {
|
||||
const validTypes = ['image/png', 'image/jpeg', 'image/webp'];
|
||||
mimeType = validTypes.includes(mimeType) ? mimeType : 'image/png';
|
||||
quality = Math.min(1, Math.max(0, Number(quality))) || .8;
|
||||
|
||||
await Promise.all(this.imagePromises);
|
||||
// 清空画布
|
||||
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
|
||||
|
||||
// 绘制所有图片
|
||||
this.images.sort((a, b) => a.zIndex - b.zIndex)
|
||||
this.images.forEach(({ img, x, y, zIndex }) => {
|
||||
this.ctx.drawImage(img, x, y);
|
||||
});
|
||||
|
||||
const b64 = this.canvas.toDataURL(mimeType, quality)
|
||||
|
||||
this.images.length = 0;
|
||||
|
||||
Reference in New Issue
Block a user