JavaScript新手添加页面水印时遭遇'Uncaught ReferenceError: watermark is not defined'错误的排查与解决咨询
Hey there! Let's fix that Uncaught ReferenceError: watermark is not defined issue you're facing with your JavaScript watermark code.
That error pops up because your browser has no idea what the watermark function is—you're trying to use a third-party watermark library, but haven't loaded it into your page yet. Let's break down the fixes step by step:
Why This Happens
Your code calls watermark() right away, but there's no JavaScript library included that provides this function. Browsers can't guess where functions come from, so it throws a reference error when it can't find the one you're using.
Fix Steps
Add the Watermark Library
You're likely usingwatermarkjs, a popular tool for this kind of task. Add this script tag to your<head>section to load it via CDN (the easiest way to get started):<script src="https://cdnjs.cloudflare.com/ajax/libs/watermarkjs/2.3.1/watermark.min.js"></script>Alternatively, you can download the library file and host it locally, then use a relative path to reference it in your HTML.
Fix the Missing DOM Element
Your code tries to append the watermarked image to an element withid="center", but that element doesn't exist in your current HTML. Add this container somewhere in your<body>:<div id="center" style="text-align: center;"></div>
Full Corrected Code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>WaterMArk</title> <!-- Load watermarkjs library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/watermarkjs/2.3.1/watermark.min.js"></script> </head> <body> <h1 style="text-align: center;">Watermark</h1> <hr /> <!-- Container for the watermarked image --> <div id="center" style="text-align: center;"></div> <script> watermark(['img/f.jpg', 'img/grator1.png']) .image(watermark.image.center(0.5)) .then(function (img) { document.getElementById('center').appendChild(img); }); </script> </body> </html>
Quick Checks to Avoid Other Issues
- Double-check that your image paths (
img/f.jpgandimg/grator1.png) are correct. If the images can't load, the watermark won't generate properly. - Make sure the library loads before your custom script runs (placing the library script in the
<head>ensures this).
内容的提问来源于stack exchange,提问作者Monu Patil

