watermark-js-plus 0.0.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,506 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.watermark = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ /******************************************************************************
8
+ Copyright (c) Microsoft Corporation.
9
+
10
+ Permission to use, copy, modify, and/or distribute this software for any
11
+ purpose with or without fee is hereby granted.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
14
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
16
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
17
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
18
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
19
+ PERFORMANCE OF THIS SOFTWARE.
20
+ ***************************************************************************** */
21
+ /* global Reflect, Promise */
22
+
23
+ var extendStatics = function(d, b) {
24
+ extendStatics = Object.setPrototypeOf ||
25
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
27
+ return extendStatics(d, b);
28
+ };
29
+
30
+ function __extends(d, b) {
31
+ if (typeof b !== "function" && b !== null)
32
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
33
+ extendStatics(d, b);
34
+ function __() { this.constructor = d; }
35
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
36
+ }
37
+
38
+ function __awaiter(thisArg, _arguments, P, generator) {
39
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
40
+ return new (P || (P = Promise))(function (resolve, reject) {
41
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
42
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
43
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
44
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
45
+ });
46
+ }
47
+
48
+ function __generator(thisArg, body) {
49
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
50
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
51
+ function verb(n) { return function (v) { return step([n, v]); }; }
52
+ function step(op) {
53
+ if (f) throw new TypeError("Generator is already executing.");
54
+ while (_) try {
55
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
56
+ if (y = 0, t) op = [op[0] & 2, t.value];
57
+ switch (op[0]) {
58
+ case 0: case 1: t = op; break;
59
+ case 4: _.label++; return { value: op[1], done: false };
60
+ case 5: _.label++; y = op[1]; op = [0]; continue;
61
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
62
+ default:
63
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
64
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
65
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
66
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
67
+ if (t[2]) _.ops.pop();
68
+ _.trys.pop(); continue;
69
+ }
70
+ op = body.call(thisArg, _);
71
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
72
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
73
+ }
74
+ }
75
+
76
+ var convertImage = function (canvas) {
77
+ return canvas.toDataURL('image/png', 1);
78
+ };
79
+ var isFunction = function (value) {
80
+ return typeof value === 'function';
81
+ };
82
+ var createSVGElement = function (tagName, attrs, namespaceURI) {
83
+ if (attrs === void 0) { attrs = {}; }
84
+ if (namespaceURI === void 0) { namespaceURI = 'http://www.w3.org/2000/svg'; }
85
+ var element = document.createElementNS(namespaceURI, tagName);
86
+ for (var attr in attrs) {
87
+ element.setAttribute(attr, attrs[attr]);
88
+ }
89
+ return element;
90
+ };
91
+ var getMultiLineData = function (ctx, text, maxWidth) {
92
+ var result = [];
93
+ var str = '';
94
+ for (var i = 0, len = text.length; i < len; i++) {
95
+ str += text.charAt(i);
96
+ if (ctx.measureText(str).width > maxWidth) {
97
+ result.push(str.substring(0, str.length - 1));
98
+ str = '';
99
+ i--;
100
+ }
101
+ }
102
+ result.push(str);
103
+ return result;
104
+ };
105
+ var createCustomContentSVG = function (ctx, options) {
106
+ var svgElement = createSVGElement('svg', {
107
+ xmlns: 'http://www.w3.org/2000/svg'
108
+ });
109
+ var foreignObjectElement = createSVGElement('foreignObject', {
110
+ width: options.width.toString(),
111
+ height: options.height.toString()
112
+ });
113
+ var bodyElement = document.createElement('div');
114
+ bodyElement.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
115
+ bodyElement.style.cssText = "\n text-align: center;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 100%;\n height: 100%;\n font: ".concat(ctx.font, ";\n color: ").concat(options.fontColor, ";\n ");
116
+ bodyElement.innerHTML = options.content;
117
+ foreignObjectElement.appendChild(bodyElement);
118
+ svgElement.appendChild(foreignObjectElement);
119
+ return svgElement;
120
+ };
121
+ var convertSVGToImage = function (svg) {
122
+ var richContent = svg.outerHTML.replace(/\n/g, '').replace(/\t/g, '').replace(/#/g, '%23');
123
+ return "data:image/svg+xml;charset=utf-8,".concat(richContent);
124
+ };
125
+
126
+ var ContentTypeEnum;
127
+ (function (ContentTypeEnum) {
128
+ ContentTypeEnum["text"] = "text";
129
+ ContentTypeEnum["image"] = "image";
130
+ ContentTypeEnum["multiLineText"] = "multi-line-text";
131
+ ContentTypeEnum["richText"] = "rich-text";
132
+ })(ContentTypeEnum || (ContentTypeEnum = {}));
133
+ var TextAlignEnum;
134
+ (function (TextAlignEnum) {
135
+ TextAlignEnum["center"] = "center";
136
+ TextAlignEnum["left"] = "left";
137
+ TextAlignEnum["right"] = "right";
138
+ })(TextAlignEnum || (TextAlignEnum = {}));
139
+ var TextBaselineEnum;
140
+ (function (TextBaselineEnum) {
141
+ TextBaselineEnum["top"] = "top";
142
+ TextBaselineEnum["bottom"] = "bottom";
143
+ TextBaselineEnum["middle"] = "middle";
144
+ })(TextBaselineEnum || (TextBaselineEnum = {}));
145
+ var CreateWatermarkModeEnum;
146
+ (function (CreateWatermarkModeEnum) {
147
+ CreateWatermarkModeEnum["default"] = "default";
148
+ CreateWatermarkModeEnum["blind"] = "blind";
149
+ })(CreateWatermarkModeEnum || (CreateWatermarkModeEnum = {}));
150
+ var DecodeBlindWatermarkModeEnum;
151
+ (function (DecodeBlindWatermarkModeEnum) {
152
+ DecodeBlindWatermarkModeEnum["canvas"] = "canvas";
153
+ DecodeBlindWatermarkModeEnum["html"] = "html";
154
+ DecodeBlindWatermarkModeEnum["svg"] = "svg";
155
+ })(DecodeBlindWatermarkModeEnum || (DecodeBlindWatermarkModeEnum = {}));
156
+
157
+ /**
158
+ * Watermark class
159
+ */
160
+ var Watermark = /** @class */ (function () {
161
+ /**
162
+ * Watermark constructor
163
+ * @param props - watermark options
164
+ */
165
+ function Watermark(props) {
166
+ if (props === void 0) { props = {}; }
167
+ var _a;
168
+ this.parentElement = document.body;
169
+ this.options = Object.assign({
170
+ width: 300,
171
+ height: 300,
172
+ rotate: 45,
173
+ contentType: ContentTypeEnum.text,
174
+ content: 'hello watermark-js-plus',
175
+ imageWidth: 0,
176
+ imageHeight: 0,
177
+ lineHeight: 30,
178
+ zIndex: 10000,
179
+ backgroundPosition: '0 0, 0 0',
180
+ backgroundRepeat: 'repeat',
181
+ fontSize: 20,
182
+ fontFamily: 'sans-serif',
183
+ textAlign: TextAlignEnum.center,
184
+ textBaseline: TextBaselineEnum.middle,
185
+ fontColor: '#000',
186
+ globalAlpha: 0.5,
187
+ fontWeight: 'normal',
188
+ mode: CreateWatermarkModeEnum.default,
189
+ mutationObserve: true,
190
+ unique: true,
191
+ parent: 'body',
192
+ onSuccess: function () { },
193
+ onBeforeDestroy: function () { },
194
+ onDestroyed: function () { }
195
+ }, props);
196
+ if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.rotate) {
197
+ this.options.rotate = (360 - this.options.rotate % 360) * (Math.PI / 180);
198
+ }
199
+ this.changeParentElement(this.options.parent);
200
+ }
201
+ /**
202
+ * Create an HD canvas.
203
+ * @param width - width of canvas
204
+ * @param height - height of canvas
205
+ */
206
+ Watermark.createCanvas = function (width, height) {
207
+ var _a;
208
+ var ratio = window.devicePixelRatio || 1;
209
+ var canvas = document.createElement('canvas');
210
+ canvas.width = width * ratio; // actual rendered pixel
211
+ canvas.height = height * ratio; // actual rendered pixel
212
+ canvas.style.width = "".concat(width, "px"); // control display size
213
+ canvas.style.height = "".concat(height, "px"); // control display size
214
+ (_a = canvas.getContext('2d')) === null || _a === void 0 ? void 0 : _a.setTransform(ratio, 0, 0, ratio, 0, 0);
215
+ return canvas;
216
+ };
217
+ Watermark.prototype.changeParentElement = function (parent) {
218
+ if (typeof parent === 'string') {
219
+ var parentElement = document.querySelector(parent);
220
+ parentElement && (this.parentElement = parentElement);
221
+ }
222
+ else {
223
+ this.parentElement = parent;
224
+ }
225
+ };
226
+ /**
227
+ * Creating a watermark.
228
+ */
229
+ Watermark.prototype.create = function () {
230
+ var _a, _b;
231
+ return __awaiter(this, void 0, void 0, function () {
232
+ var canvas, image, watermarkInnerDom, parentElementType;
233
+ return __generator(this, function (_c) {
234
+ switch (_c.label) {
235
+ case 0:
236
+ if (!this.validateUnique()) {
237
+ return [2 /*return*/];
238
+ }
239
+ if (!this.validateContent()) {
240
+ return [2 /*return*/];
241
+ }
242
+ return [4 /*yield*/, this.draw()];
243
+ case 1:
244
+ canvas = _c.sent();
245
+ image = convertImage(canvas);
246
+ this.watermarkDom = document.createElement('div');
247
+ watermarkInnerDom = document.createElement('div');
248
+ this.watermarkDom.__WATERMARK__ = 'watermark';
249
+ this.watermarkDom.__WATERMARK__INSTANCE__ = this;
250
+ parentElementType = this.checkParentElementType();
251
+ this.watermarkDom.style.cssText = "\n z-index: ".concat(this.options.zIndex, ";\n ").concat(parentElementType === 'custom' ? 'top: 0;bottom: 0;left: 0;right: 0;height: 100%;pointer-events: none;position: absolute' : 'position: relative', "\n ");
252
+ watermarkInnerDom.style.cssText = "\n position: ".concat(parentElementType === 'root' ? 'fixed;' : 'absolute;', "\n z-index: ").concat(this.options.zIndex, ";\n pointer-events: none;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n background-image: url(").concat(image, ");\n background-repeat: ").concat(this.options.backgroundRepeat, ";\n background-size: ").concat(this.options.width, "px ").concat(this.options.height, "px;\n background-position: ").concat(this.options.backgroundPosition, ";\n -webkit-print-color-adjust: exact;\n ");
253
+ this.watermarkDom.append(watermarkInnerDom);
254
+ this.parentElement.appendChild(this.watermarkDom);
255
+ if (this.options.mutationObserve) {
256
+ this.bindMutationObserve();
257
+ }
258
+ (_b = (_a = this.options).onSuccess) === null || _b === void 0 ? void 0 : _b.call(_a);
259
+ return [2 /*return*/];
260
+ }
261
+ });
262
+ });
263
+ };
264
+ /**
265
+ * Deleting this watermark.
266
+ */
267
+ Watermark.prototype.destroy = function () {
268
+ var _a, _b, _c, _d, _e, _f, _g;
269
+ (_b = (_a = this.options).onBeforeDestroy) === null || _b === void 0 ? void 0 : _b.call(_a);
270
+ (_c = this.observer) === null || _c === void 0 ? void 0 : _c.disconnect();
271
+ (_d = this.parentObserve) === null || _d === void 0 ? void 0 : _d.disconnect();
272
+ (_e = this.watermarkDom) === null || _e === void 0 ? void 0 : _e.remove();
273
+ (_g = (_f = this.options).onDestroyed) === null || _g === void 0 ? void 0 : _g.call(_f);
274
+ };
275
+ Watermark.prototype.validateUnique = function () {
276
+ var result = true;
277
+ if (this.options.unique) {
278
+ this.parentElement.childNodes.forEach(function (node) {
279
+ if (!result) {
280
+ return;
281
+ }
282
+ if (Object.hasOwnProperty.call(node, '__WATERMARK__')) {
283
+ result = false;
284
+ // throw new Error('duplicate watermark error')
285
+ }
286
+ });
287
+ }
288
+ return result;
289
+ };
290
+ Watermark.prototype.validateContent = function () {
291
+ switch (this.options.contentType) {
292
+ case ContentTypeEnum.image:
293
+ return Object.hasOwnProperty.call(this.options, 'image');
294
+ case ContentTypeEnum.multiLineText:
295
+ case ContentTypeEnum.richText:
296
+ case ContentTypeEnum.text:
297
+ return this.options.content.length > 0;
298
+ }
299
+ return false;
300
+ };
301
+ Watermark.prototype.draw = function () {
302
+ var _this = this;
303
+ var canvas = Watermark.createCanvas(this.options.width, this.options.height);
304
+ // document.body?.appendChild(canvas)
305
+ var ctx = canvas.getContext('2d');
306
+ if (ctx === null) {
307
+ throw new Error('get context error');
308
+ }
309
+ ctx.font = "".concat(this.options.fontWeight, " ").concat(this.options.fontSize, "px ").concat(this.options.fontFamily);
310
+ ctx.textAlign = this.options.textAlign;
311
+ ctx.textBaseline = this.options.textBaseline;
312
+ ctx.fillStyle = this.options.fontColor;
313
+ ctx.globalAlpha = this.options.globalAlpha;
314
+ return new Promise(function (resolve) {
315
+ switch (_this.options.contentType) {
316
+ case ContentTypeEnum.text:
317
+ _this.drawText(ctx, resolve);
318
+ break;
319
+ case ContentTypeEnum.image:
320
+ _this.drawImage(ctx, resolve);
321
+ break;
322
+ case ContentTypeEnum.multiLineText:
323
+ _this.drawMultiLineText(ctx, resolve);
324
+ break;
325
+ case ContentTypeEnum.richText:
326
+ _this.drawRichText(ctx, resolve);
327
+ break;
328
+ }
329
+ });
330
+ };
331
+ Watermark.prototype.drawText = function (ctx, resolve) {
332
+ ctx.translate(this.options.width / 2, this.options.height / 2);
333
+ ctx.rotate(this.options.rotate);
334
+ ctx.fillText(this.options.content, 0, 0);
335
+ resolve(ctx.canvas);
336
+ };
337
+ Watermark.prototype.drawImage = function (ctx, resolve) {
338
+ var _this = this;
339
+ var image = new Image();
340
+ image.setAttribute('crossOrigin', 'Anonymous');
341
+ image.src = this.options.image;
342
+ image.onload = function () {
343
+ ctx.translate(_this.options.width / 2, _this.options.height / 2);
344
+ ctx.rotate(_this.options.rotate);
345
+ var _a = _this.getImageRect(image), imageWidth = _a.width, imageHeight = _a.height;
346
+ ctx.drawImage(image, 0 - imageWidth / 2, 0 - imageHeight / 2, imageWidth, imageHeight);
347
+ resolve(ctx.canvas);
348
+ };
349
+ };
350
+ Watermark.prototype.drawMultiLineText = function (ctx, resolve) {
351
+ var _this = this;
352
+ // image.width = this.options.width
353
+ // image.height = this.options.height
354
+ // const element = createCustomContentSvg(context, this.options)
355
+ // image.src = convertSVGToImage(element)
356
+ // image.onload = () => {
357
+ // context.translate(this.options.width / 2, this.options.height / 2)
358
+ // context.rotate(this.options.rotate)
359
+ // context.drawImage(
360
+ // image,
361
+ // -this.options.width / 2,
362
+ // -this.options.height / 2,
363
+ // context.canvas.width,
364
+ // context.canvas.height
365
+ // )
366
+ // resolve(canvas)
367
+ // }
368
+ var lines = getMultiLineData(ctx, this.options.content, this.options.width);
369
+ ctx.translate(this.options.width / 2, this.options.height / 2);
370
+ ctx.rotate(this.options.rotate);
371
+ var yOffsetValue = (lines.length - 1) * this.options.lineHeight / 2;
372
+ lines.forEach(function (txt, index) {
373
+ ctx.fillText(txt, 0, _this.options.lineHeight * index - yOffsetValue);
374
+ });
375
+ resolve(ctx.canvas);
376
+ };
377
+ Watermark.prototype.drawRichText = function (ctx, resolve) {
378
+ var _this = this;
379
+ var image = new Image();
380
+ image.width = this.options.width;
381
+ image.height = this.options.height;
382
+ var element = createCustomContentSVG(ctx, this.options);
383
+ image.src = convertSVGToImage(element);
384
+ image.onload = function () {
385
+ ctx.translate(_this.options.width / 2, _this.options.height / 2);
386
+ ctx.rotate(_this.options.rotate);
387
+ ctx.drawImage(image, -_this.options.width / 2, -_this.options.height / 2, ctx.canvas.width, ctx.canvas.height);
388
+ resolve(ctx.canvas);
389
+ };
390
+ };
391
+ Watermark.prototype.getImageRect = function (image) {
392
+ var rect = { width: this.options.imageWidth, height: this.options.imageHeight };
393
+ switch (true) {
394
+ case rect.width !== 0 && rect.height === 0:
395
+ rect.height = rect.width * image.height / image.width;
396
+ break;
397
+ case rect.width === 0 && rect.height !== 0:
398
+ rect.width = rect.height * image.width / image.height;
399
+ break;
400
+ case rect.width === 0 && rect.height === 0:
401
+ rect.width = image.width;
402
+ rect.height = image.height;
403
+ break;
404
+ }
405
+ return rect;
406
+ };
407
+ Watermark.prototype.checkParentElementType = function () {
408
+ if (['html', 'body'].includes(this.parentElement.tagName.toLocaleLowerCase())) {
409
+ return 'root';
410
+ }
411
+ return 'custom';
412
+ };
413
+ Watermark.prototype.bindMutationObserve = function () {
414
+ var _this = this;
415
+ if (!this.watermarkDom) {
416
+ return;
417
+ }
418
+ this.observer = new MutationObserver(function (mutationsList) {
419
+ if (mutationsList.length > 0) {
420
+ _this.destroy();
421
+ _this.create();
422
+ }
423
+ });
424
+ this.observer.observe(this.watermarkDom, {
425
+ attributes: true,
426
+ childList: true,
427
+ subtree: true,
428
+ characterData: true // 节点内容或节点文本的变动。
429
+ });
430
+ this.parentObserve = new MutationObserver(function (mutationsList) {
431
+ mutationsList.forEach(function (item) {
432
+ var _a;
433
+ if ((item === null || item === void 0 ? void 0 : item.target) === _this.watermarkDom || ((_a = item === null || item === void 0 ? void 0 : item.removedNodes) === null || _a === void 0 ? void 0 : _a[0]) === _this.watermarkDom) {
434
+ _this.destroy();
435
+ _this.create();
436
+ }
437
+ });
438
+ });
439
+ this.parentObserve.observe(this.parentElement, {
440
+ attributes: true,
441
+ childList: true,
442
+ subtree: true,
443
+ characterData: true // 节点内容或节点文本的变动。
444
+ });
445
+ };
446
+ return Watermark;
447
+ }());
448
+
449
+ /**
450
+ * BlindWatermark class
451
+ */
452
+ var BlindWatermark = /** @class */ (function (_super) {
453
+ __extends(BlindWatermark, _super);
454
+ /**
455
+ * BlindWatermark constructor
456
+ * @param props - blind watermark options
457
+ */
458
+ function BlindWatermark(props) {
459
+ if (props === void 0) { props = {}; }
460
+ props.globalAlpha = 0.005;
461
+ props.mode = CreateWatermarkModeEnum.blind;
462
+ return _super.call(this, props) || this;
463
+ }
464
+ /**
465
+ * Decode blind watermark.
466
+ * @param props - decode options
467
+ */
468
+ BlindWatermark.decode = function (props) {
469
+ var options = Object.assign({
470
+ url: '',
471
+ fillColor: '#000',
472
+ compositeOperation: 'color-burn',
473
+ mode: DecodeBlindWatermarkModeEnum.canvas
474
+ }, props);
475
+ if (!options.url) {
476
+ return;
477
+ }
478
+ if (options.mode === DecodeBlindWatermarkModeEnum.canvas) {
479
+ var img_1 = new Image();
480
+ img_1.src = options.url;
481
+ img_1.onload = function () {
482
+ var _a;
483
+ var width = img_1.width, height = img_1.height;
484
+ var canvas = Watermark.createCanvas(width, height);
485
+ var ctx = canvas.getContext('2d');
486
+ if (ctx === null) {
487
+ throw new Error('get context error');
488
+ }
489
+ ctx.drawImage(img_1, 0, 0, width, height);
490
+ ctx.globalCompositeOperation = options.compositeOperation;
491
+ ctx.fillStyle = options.fillColor;
492
+ ctx.fillRect(0, 0, width, height);
493
+ var resultImage = convertImage(canvas);
494
+ if (options.onSuccess && isFunction(options.onSuccess)) {
495
+ (_a = options.onSuccess) === null || _a === void 0 ? void 0 : _a.call(options, resultImage);
496
+ }
497
+ };
498
+ }
499
+ };
500
+ return BlindWatermark;
501
+ }(Watermark));
502
+
503
+ exports.BlindWatermark = BlindWatermark;
504
+ exports.Watermark = Watermark;
505
+
506
+ }));
@@ -0,0 +1 @@
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).watermark={})}(this,(function(t){"use strict";var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},e(t,n)};function n(t,e,n,o){return new(n||(n=Promise))((function(i,r){function a(t){try{c(o.next(t))}catch(t){r(t)}}function s(t){try{c(o.throw(t))}catch(t){r(t)}}function c(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,s)}c((o=o.apply(t,e||[])).next())}))}function o(t,e){var n,o,i,r,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return r={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function s(r){return function(s){return function(r){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,o&&(i=2&r[0]?o.return:r[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,r[1])).done)return i;switch(o=0,i&&(r=[2&r[0],i.value]),r[0]){case 0:case 1:i=r;break;case 4:return a.label++,{value:r[1],done:!1};case 5:a.label++,o=r[1],r=[0];continue;case 7:r=a.ops.pop(),a.trys.pop();continue;default:if(!(i=a.trys,(i=i.length>0&&i[i.length-1])||6!==r[0]&&2!==r[0])){a=0;continue}if(3===r[0]&&(!i||r[1]>i[0]&&r[1]<i[3])){a.label=r[1];break}if(6===r[0]&&a.label<i[1]){a.label=i[1],i=r;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(r);break}i[2]&&a.ops.pop(),a.trys.pop();continue}r=e.call(t,a)}catch(t){r=[6,t],o=0}finally{n=i=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,s])}}}var i,r,a,s,c,h=function(t){return t.toDataURL("image/png",1)},l=function(t,e,n){void 0===e&&(e={}),void 0===n&&(n="http://www.w3.org/2000/svg");var o=document.createElementNS(n,t);for(var i in e)o.setAttribute(i,e[i]);return o};!function(t){t.text="text",t.image="image",t.multiLineText="multi-line-text",t.richText="rich-text"}(i||(i={})),function(t){t.center="center",t.left="left",t.right="right"}(r||(r={})),function(t){t.top="top",t.bottom="bottom",t.middle="middle"}(a||(a={})),function(t){t.default="default",t.blind="blind"}(s||(s={})),function(t){t.canvas="canvas",t.html="html",t.svg="svg"}(c||(c={}));var u=function(){function t(t){var e;void 0===t&&(t={}),this.parentElement=document.body,this.options=Object.assign({width:300,height:300,rotate:45,contentType:i.text,content:"hello watermark-js-plus",imageWidth:0,imageHeight:0,lineHeight:30,zIndex:1e4,backgroundPosition:"0 0, 0 0",backgroundRepeat:"repeat",fontSize:20,fontFamily:"sans-serif",textAlign:r.center,textBaseline:a.middle,fontColor:"#000",globalAlpha:.5,fontWeight:"normal",mode:s.default,mutationObserve:!0,unique:!0,parent:"body",onSuccess:function(){},onBeforeDestroy:function(){},onDestroyed:function(){}},t),(null===(e=this.options)||void 0===e?void 0:e.rotate)&&(this.options.rotate=(360-this.options.rotate%360)*(Math.PI/180)),this.changeParentElement(this.options.parent)}return t.createCanvas=function(t,e){var n,o=window.devicePixelRatio||1,i=document.createElement("canvas");return i.width=t*o,i.height=e*o,i.style.width="".concat(t,"px"),i.style.height="".concat(e,"px"),null===(n=i.getContext("2d"))||void 0===n||n.setTransform(o,0,0,o,0,0),i},t.prototype.changeParentElement=function(t){if("string"==typeof t){var e=document.querySelector(t);e&&(this.parentElement=e)}else this.parentElement=t},t.prototype.create=function(){var t,e;return n(this,void 0,void 0,(function(){var n,i,r,a;return o(this,(function(o){switch(o.label){case 0:return this.validateUnique()&&this.validateContent()?[4,this.draw()]:[2];case 1:return n=o.sent(),i=h(n),this.watermarkDom=document.createElement("div"),r=document.createElement("div"),this.watermarkDom.__WATERMARK__="watermark",this.watermarkDom.__WATERMARK__INSTANCE__=this,a=this.checkParentElementType(),this.watermarkDom.style.cssText="\n z-index: ".concat(this.options.zIndex,";\n ").concat("custom"===a?"top: 0;bottom: 0;left: 0;right: 0;height: 100%;pointer-events: none;position: absolute":"position: relative","\n "),r.style.cssText="\n position: ".concat("root"===a?"fixed;":"absolute;","\n z-index: ").concat(this.options.zIndex,";\n pointer-events: none;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n background-image: url(").concat(i,");\n background-repeat: ").concat(this.options.backgroundRepeat,";\n background-size: ").concat(this.options.width,"px ").concat(this.options.height,"px;\n background-position: ").concat(this.options.backgroundPosition,";\n -webkit-print-color-adjust: exact;\n "),this.watermarkDom.append(r),this.parentElement.appendChild(this.watermarkDom),this.options.mutationObserve&&this.bindMutationObserve(),null===(e=(t=this.options).onSuccess)||void 0===e||e.call(t),[2]}}))}))},t.prototype.destroy=function(){var t,e,n,o,i,r,a;null===(e=(t=this.options).onBeforeDestroy)||void 0===e||e.call(t),null===(n=this.observer)||void 0===n||n.disconnect(),null===(o=this.parentObserve)||void 0===o||o.disconnect(),null===(i=this.watermarkDom)||void 0===i||i.remove(),null===(a=(r=this.options).onDestroyed)||void 0===a||a.call(r)},t.prototype.validateUnique=function(){var t=!0;return this.options.unique&&this.parentElement.childNodes.forEach((function(e){t&&Object.hasOwnProperty.call(e,"__WATERMARK__")&&(t=!1)})),t},t.prototype.validateContent=function(){switch(this.options.contentType){case i.image:return Object.hasOwnProperty.call(this.options,"image");case i.multiLineText:case i.richText:case i.text:return this.options.content.length>0}return!1},t.prototype.draw=function(){var e=this,n=t.createCanvas(this.options.width,this.options.height).getContext("2d");if(null===n)throw new Error("get context error");return n.font="".concat(this.options.fontWeight," ").concat(this.options.fontSize,"px ").concat(this.options.fontFamily),n.textAlign=this.options.textAlign,n.textBaseline=this.options.textBaseline,n.fillStyle=this.options.fontColor,n.globalAlpha=this.options.globalAlpha,new Promise((function(t){switch(e.options.contentType){case i.text:e.drawText(n,t);break;case i.image:e.drawImage(n,t);break;case i.multiLineText:e.drawMultiLineText(n,t);break;case i.richText:e.drawRichText(n,t)}}))},t.prototype.drawText=function(t,e){t.translate(this.options.width/2,this.options.height/2),t.rotate(this.options.rotate),t.fillText(this.options.content,0,0),e(t.canvas)},t.prototype.drawImage=function(t,e){var n=this,o=new Image;o.setAttribute("crossOrigin","Anonymous"),o.src=this.options.image,o.onload=function(){t.translate(n.options.width/2,n.options.height/2),t.rotate(n.options.rotate);var i=n.getImageRect(o),r=i.width,a=i.height;t.drawImage(o,0-r/2,0-a/2,r,a),e(t.canvas)}},t.prototype.drawMultiLineText=function(t,e){var n=this,o=function(t,e,n){for(var o=[],i="",r=0,a=e.length;r<a;r++)i+=e.charAt(r),t.measureText(i).width>n&&(o.push(i.substring(0,i.length-1)),i="",r--);return o.push(i),o}(t,this.options.content,this.options.width);t.translate(this.options.width/2,this.options.height/2),t.rotate(this.options.rotate);var i=(o.length-1)*this.options.lineHeight/2;o.forEach((function(e,o){t.fillText(e,0,n.options.lineHeight*o-i)})),e(t.canvas)},t.prototype.drawRichText=function(t,e){var n=this,o=new Image;o.width=this.options.width,o.height=this.options.height;var i,r=function(t,e){var n=l("svg",{xmlns:"http://www.w3.org/2000/svg"}),o=l("foreignObject",{width:e.width.toString(),height:e.height.toString()}),i=document.createElement("div");return i.setAttribute("xmlns","http://www.w3.org/1999/xhtml"),i.style.cssText="\n text-align: center;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 100%;\n height: 100%;\n font: ".concat(t.font,";\n color: ").concat(e.fontColor,";\n "),i.innerHTML=e.content,o.appendChild(i),n.appendChild(o),n}(t,this.options);o.src=(i=r.outerHTML.replace(/\n/g,"").replace(/\t/g,"").replace(/#/g,"%23"),"data:image/svg+xml;charset=utf-8,".concat(i)),o.onload=function(){t.translate(n.options.width/2,n.options.height/2),t.rotate(n.options.rotate),t.drawImage(o,-n.options.width/2,-n.options.height/2,t.canvas.width,t.canvas.height),e(t.canvas)}},t.prototype.getImageRect=function(t){var e={width:this.options.imageWidth,height:this.options.imageHeight};switch(!0){case 0!==e.width&&0===e.height:e.height=e.width*t.height/t.width;break;case 0===e.width&&0!==e.height:e.width=e.height*t.width/t.height;break;case 0===e.width&&0===e.height:e.width=t.width,e.height=t.height}return e},t.prototype.checkParentElementType=function(){return["html","body"].includes(this.parentElement.tagName.toLocaleLowerCase())?"root":"custom"},t.prototype.bindMutationObserve=function(){var t=this;this.watermarkDom&&(this.observer=new MutationObserver((function(e){e.length>0&&(t.destroy(),t.create())})),this.observer.observe(this.watermarkDom,{attributes:!0,childList:!0,subtree:!0,characterData:!0}),this.parentObserve=new MutationObserver((function(e){e.forEach((function(e){var n;(null==e?void 0:e.target)!==t.watermarkDom&&(null===(n=null==e?void 0:e.removedNodes)||void 0===n?void 0:n[0])!==t.watermarkDom||(t.destroy(),t.create())}))})),this.parentObserve.observe(this.parentElement,{attributes:!0,childList:!0,subtree:!0,characterData:!0}))},t}(),p=function(t){function n(e){return void 0===e&&(e={}),e.globalAlpha=.005,e.mode=s.blind,t.call(this,e)||this}return function(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function o(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(o.prototype=n.prototype,new o)}(n,t),n.decode=function(t){var e=Object.assign({url:"",fillColor:"#000",compositeOperation:"color-burn",mode:c.canvas},t);if(e.url&&e.mode===c.canvas){var n=new Image;n.src=e.url,n.onload=function(){var t,o=n.width,i=n.height,r=u.createCanvas(o,i),a=r.getContext("2d");if(null===a)throw new Error("get context error");a.drawImage(n,0,0,o,i),a.globalCompositeOperation=e.compositeOperation,a.fillStyle=e.fillColor,a.fillRect(0,0,o,i);var s=h(r);e.onSuccess&&"function"==typeof e.onSuccess&&(null===(t=e.onSuccess)||void 0===t||t.call(e,s))}}},n}(u);t.BlindWatermark=p,t.Watermark=u}));
package/package.json CHANGED
@@ -1,16 +1,15 @@
1
1
  {
2
2
  "name": "watermark-js-plus",
3
- "version": "0.0.4",
3
+ "version": "0.2.0",
4
4
  "description": "watermark for the browser",
5
- "type": "module",
6
5
  "scripts": {
7
6
  "test": "echo \"Error: no test specified\" && exit 1",
8
7
  "prepare": "husky install",
9
8
  "lint": "npx eslint \"src/*.{ts,js}\"",
10
9
  "dev": "concurrently \"npm run src:dev\" \"npm run docs:dev\"",
11
- "src:dev": "rollup -c --watch --bundleConfigAsCjs",
12
- "build": "rollup -c --bundleConfigAsCjs --environment NODE_ENV:production",
13
- "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0 -n changelog-option.cjs",
10
+ "src:dev": "rollup -c --watch",
11
+ "build": "rollup -c --environment NODE_ENV:production",
12
+ "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0 -n changelog-option.js",
14
13
  "docs:dev": "vitepress dev docs",
15
14
  "docs:build": "vitepress build docs",
16
15
  "docs:serve": "vitepress serve docs",
@@ -36,21 +35,16 @@
36
35
  "防删除水印",
37
36
  "解密水印"
38
37
  ],
39
- "exports": {
40
- ".": {
41
- "types": "./dist/index.js",
42
- "require": "./dist/index.js",
43
- "import": "./dist/index.js"
44
- }
45
- },
46
- "main": "dist/index.js",
47
- "module": "dist/index.js",
48
- "types": "dist/index.js",
38
+ "main": "dist/watermark.esm.js",
39
+ "module": "dist/watermark.esm.js",
40
+ "browser": "dist/watermark.umd.min.js",
41
+ "unpkg": "",
42
+ "types": "dist/index.d.ts",
49
43
  "files": [
50
44
  "dist"
51
45
  ],
52
46
  "devDependencies": {
53
- "@babel/core": "^7.20.5",
47
+ "@babel/core": "^7.20.7",
54
48
  "@babel/eslint-parser": "^7.19.1",
55
49
  "@babel/plugin-transform-runtime": "^7.19.6",
56
50
  "@babel/preset-env": "^7.20.2",
@@ -58,33 +52,33 @@
58
52
  "@commitlint/config-conventional": "^17.3.0",
59
53
  "@element-plus/icons-vue": "^2.0.10",
60
54
  "@rollup/plugin-babel": "^6.0.3",
61
- "@rollup/plugin-commonjs": "^23.0.4",
55
+ "@rollup/plugin-commonjs": "^24.0.0",
62
56
  "@rollup/plugin-eslint": "^9.0.1",
63
57
  "@rollup/plugin-node-resolve": "^15.0.1",
64
- "@rollup/plugin-replace": "^5.0.1",
65
- "@rollup/plugin-terser": "^0.2.0",
58
+ "@rollup/plugin-replace": "^5.0.2",
59
+ "@rollup/plugin-terser": "0.2.1",
66
60
  "@rollup/plugin-typescript": "^10.0.1",
67
61
  "@types/markdown-it": "^12.2.3",
68
- "@typescript-eslint/parser": "^5.45.1",
62
+ "@typescript-eslint/parser": "^5.48.0",
69
63
  "@vue/theme": "^1.3.0",
70
64
  "concurrently": "^7.6.0",
71
65
  "conventional-changelog-angular": "^5.0.13",
72
66
  "conventional-changelog-cli": "^2.2.2",
73
- "core-js": "^3.26.1",
74
- "element-plus": "^2.2.26",
75
- "eslint": "^8.29.0",
67
+ "core-js": "^3.27.1",
68
+ "element-plus": "^2.2.28",
69
+ "eslint": "^8.31.0",
76
70
  "eslint-config-airbnb-base": "^15.0.0",
77
71
  "eslint-config-semistandard": "^17.0.0",
78
72
  "eslint-plugin-import": "^2.26.0",
79
- "husky": "^8.0.2",
73
+ "husky": "^8.0.3",
80
74
  "lint-staged": "^13.1.0",
81
75
  "markdown-it": "^13.0.1",
82
- "rollup": "^3.7.0",
76
+ "rollup": "^3.9.1",
83
77
  "rollup-plugin-filesize": "^9.1.2",
84
- "rollup-plugin-your-function": "^0.4.3",
78
+ "rollup-plugin-your-function": "^0.4.6",
85
79
  "terser": "^5.16.1",
86
80
  "typescript": "^4.9.4",
87
81
  "unplugin-element-plus": "^0.4.1",
88
- "vitepress": "^1.0.0-alpha.30"
82
+ "vitepress": "^1.0.0-alpha.34"
89
83
  }
90
84
  }