MathJax未定义及MathJax.tex2svg不存在问题技术求助
Let’s break down the issues in your code and walk through the fixes step by step:
1. Async Loading Timing Issue
Your MathJax script uses the async attribute, which means it loads in the background while your main code runs. When your script tries to call MathJax.tex2svg, MathJax hasn’t finished initializing yet—this is why you’re seeing the "not defined" errors.
MathJax 3 provides a built-in promise (MathJax.startup.promise) that resolves once the library is fully ready. We’ll use this to wait for MathJax before executing our code.
2. Incorrect Image Handling
You tried to attach a load event listener directly to a base64 string, which won’t work. You need to create a proper Image object, set its source to the base64 data, and then draw it once it finishes loading.
3. DOM Order Problem
Your script runs before the canvas element is rendered in the DOM. We’ll wrap our code in a DOMContentLoaded listener to ensure the canvas exists when we try to access it.
Corrected Full Code
<canvas id="surface">Canvas not Supported</canvas> <script type="text/javascript" id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js"></script> <script> // Wait for the entire DOM to load first document.addEventListener('DOMContentLoaded', async () => { // Wait for MathJax to finish initializing completely await MathJax.startup.promise; const canvas = document.getElementById('surface'); const ctx = canvas.getContext('2d'); canvas.width = 202; canvas.height = 50; // Add explicit height to avoid drawing clipping issues const tex = "F=ma"; // Now safely call MathJax's tex2svg function const svg = MathJax.tex2svg(tex); const svgElement = svg.childNodes[0]; // Convert SVG to base64-encoded image data const ssvg = new XMLSerializer().serializeToString(svgElement); const base64 = "data:image/svg+xml;base64," + window.btoa(unescape(encodeURIComponent(ssvg))); // Create an Image object to load the base64 data const img = new Image(); img.addEventListener("load", () => { ctx.drawImage(img, 105, 15, 102.3, 23.93); }); img.src = base64; // Trigger the image load by setting the source }); </script>
Key Fixes Explained:
- Wrapped code in
DOMContentLoadedto ensure the canvas is available when we access it. - Used
await MathJax.startup.promiseto guarantee MathJax is fully initialized before callingtex2svg. - Replaced the invalid base64 event listener with a proper
Imageobject, which supports theloadevent. - Added an explicit canvas height to prevent drawing from being clipped (canvases default to 300x150 if dimensions aren’t set).
内容的提问来源于stack exchange,提问作者wilsonw

