watermark.js 2.7 KB

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