- 
      
- 
        Save otienog1/15d9bc6fd7d4b1c5c87751fec732033d to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | function watermarkImage(elemImage, text) { | |
| // Create test image to get proper dimensions of the image. | |
| var testImage = new Image(); | |
| testImage.onload = function() { | |
| var h = testImage.height, w = testImage.width, img = new Image(); | |
| // Once the image with the SVG of the watermark is loaded... | |
| img.onload = function() { | |
| // Make canvas with image and watermark | |
| var canvas = Object.assign(document.createElement('canvas'), {width: w, height: h}); | |
| var ctx = canvas.getContext('2d'); | |
| ctx.drawImage(testImage, 0, 0); | |
| ctx.drawImage(img, 0, 0); | |
| // If PNG can't be retrieved show the error in the console | |
| try { | |
| elemImage.src = canvas.toDataURL('image/png'); | |
| } | |
| catch (e) { | |
| console.error('Cannot watermark image with text:', {src: elemImage.src, text: text, error: e}); | |
| } | |
| }; | |
| // SVG image watermark (HTML of text at bottom right) | |
| img.src = 'data:image/svg+xml;base64,' + window.btoa( | |
| '<svg xmlns="http://www.w3.org/2000/svg" height="' + h + '" width="' + w + '">' + | |
| '<foreignObject width="100%" height="100%">' + | |
| '<div xmlns="http://www.w3.org/1999/xhtml">' + | |
| '<div style="position: absolute;' + | |
| 'right: 0;' + | |
| 'bottom: 0;' + | |
| 'font-family: Tahoma;' + | |
| 'font-size: 10pt;' + | |
| 'background: #000;' + | |
| 'color: #fff;' + | |
| 'padding: 0.25em;' + | |
| 'border-radius: 0.25em;' + | |
| 'opacity: 0.6;' + | |
| 'margin: 0 0.125em 0.125em 0;' + | |
| '">' + text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">") + '</div>' + | |
| '</div>' + | |
| '</foreignObject>' + | |
| '</svg>' | |
| ); | |
| }; | |
| testImage.src = elemImage.src; | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment