watermark - 副本.js 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. export function createWaterMark(file,watermarks,option = {fontSize: 100,fillStyle: 'rgba(255, 0, 0, 0.5)'}) {
  2. const {fontSize,fillStyle} = option
  3. return new Promise(((resolve, reject) => {
  4. const reader = new FileReader();
  5. reader.onload = function (event) {
  6. const img = new Image();
  7. img.onload = function () {
  8. const canvas = document.createElement('canvas');
  9. const ctx = canvas.getContext('2d');
  10. // 设置canvas尺寸与图片一致
  11. canvas.width = img.width;
  12. canvas.height = img.height;
  13. // 绘制图片到canvas
  14. ctx.drawImage(img, 0, 0, img.width, img.height);
  15. //水印大小和颜色
  16. ctx.font = fontSize + 'px Arial';
  17. ctx.fillStyle = fillStyle;
  18. //水印起始位置,默认左下角
  19. let x = 35
  20. let y = 40
  21. // 添加水印
  22. for (let i = 0; i < watermarks.length; i++) {
  23. y = watermarkHandle(ctx, watermarks[i], canvas.width, canvas.height, fontSize, x, y)
  24. }
  25. // 将带有水印的canvas转换为Blob对象
  26. canvas.toBlob((blob) => {
  27. if (blob) {
  28. let blobToFile = new File([blob], file.name, {
  29. type: file.type,
  30. lastModified: Date.now()
  31. });
  32. resolve(blobToFile);
  33. } else {
  34. reject(new Error('Failed to create blob from canvas'));
  35. }
  36. }, 'image/png');
  37. };
  38. img.src = event.target.result;
  39. };
  40. reader.readAsDataURL(file);
  41. }));
  42. }
  43. /**
  44. * 写入水印,默认左下角 水印过长,换行 (x,y)=(0,0) 就是左下角的位置
  45. * @param {canvas画布对象} ctx
  46. * @param {单个水印} watermark
  47. * @param {图片的长宽} height
  48. * @param {图片的长宽} width
  49. * @param {水印字体大小} fontSize
  50. * @param {水印位置,默认左下角} x
  51. * @param {水印位置,默认左下角} y
  52. */
  53. export function watermarkHandle(ctx, watermark, width, height, fontSize, x, y) {
  54. //添加水印
  55. let lineHeight = fontSize + 15
  56. let line = '';
  57. const list = [];
  58. for (let i = 0; i < watermark.length; i++) {
  59. const testLine = line + watermark[i];
  60. const metrics = ctx.measureText(testLine);
  61. const testWidth = metrics.width;
  62. if (testWidth < width - fontSize && i < watermark.length - 1) {
  63. line = testLine;
  64. } else {
  65. list.push(line)
  66. line = watermark[i];
  67. }
  68. }
  69. const testLine = line + list[list.length - 1];
  70. const metrics = ctx.measureText(testLine);
  71. const testWidth = metrics.width;
  72. if (testWidth < width - fontSize) {
  73. list[list.length - 1] = list[list.length - 1] + line
  74. } else {
  75. list.push(line)
  76. }
  77. for (let i = list.length - 1; i >= 0; i--) {
  78. ctx.fillText(list[i], x, height - y);
  79. y += lineHeight;
  80. }
  81. //位置
  82. return y;
  83. }