Skip to content
On this page

Quick Start

Introduction

What is mxcad?

mxcad is a JavaScript framework for building online CAD preview and editing drawings. It is built on TypeScript and provides a set of APIs for CAD drawing preview and editing functions. These APIs enable the development of most basic CAD-related features on web pages.

The Online CAD Dream Drawing project is built on mxcad. You can click to see specific effects.

mxcad renders an mxweb format file, which is a drawing conversion program provided by the mxdraw cloud drawing development package that converts CAD drawings into mxweb files.

mxcad then processes the mxweb file, and the rendering capability is provided by the mxdraw library. mxcad depends on the rendering capability provided by the mxdraw library.

Therefore, mxcad must be used together with mxdraw. If you are not familiar with the mxdraw library, please refer to: https://mxcadx.gitee.io/mxdraw_docs/

mxdraw no longer maintains the wgh file format, and mxcad only supports rendering files in mxweb format.

Basic Usage

It is recommended to use Vite as the build tool.

html
<div style="height: 600px; overflow: hidden;"><canvas id="myCanvas"></canvas></div>
ts
import { createMxCad } from "mxcad";
// The createMxCad method should be called after the canvas element is loaded into the page document.
createMxCad({
    canvas: "#myCanvas",
    locateFile: (fileName) => new URL(`/node_modules/mxcad/dist/wasm/2d/${fileName}`, import.meta.url).href,
    // Provide the file to be opened. Note that "../assets/test.mxweb" is the relative path to the file address, 
    // and in Vite, you can obtain the correct network address of the file in this way.
    fileUrl: new URL("../assets/test.mxweb", import.meta.url).href,
    // Provide the directory path for loading fonts.
    fontspath: new URL("node_modules/mxcad/dist/fonts", import.meta.url).href,
}).then((mxcad) => {
    // Want to display another file?
    mxcad.openWebFile(new URL("../assets/test2.mxweb", import.meta.url).href);
    // Want to save the modified file?
    // (You can call it in the DOM element event function, so you can use some latest browser features to save the file)
    mxcad.saveFile();
});

Configuration of vite.config.ts:

ts
import { defineConfig } from "vite";
// Set the response header of devServe development server to support SharedArrayBuffer feature.
export default defineConfig({
    server: {
        headers: {
            "Cross-Origin-Opener-Policy": "same-origin",
            "Cross-Origin-Embedder-Policy": "require-corp",
        },
    },
});

Important Note

Since mxcad defaults to using SharedArrayBuffer, corresponding response headers need to be set on the server. The example above shows how to set it up in the Vite development server. For production servers, using Node.js as an example, the configuration would be as follows:

js
const http = require('http');
http.createServer((req, res) => {
    res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
    res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
});

If you do not want to use SharedArrayBuffer, you can choose the 2d-st directory instead of the 2d directory when using the wasm file package.

In the node_modules/mxcad/dist/wasm/ directory of mxcad, there are three wasm file packages: 2d, 2d-st, and 3d.

If you want to ensure that wasm files can be loaded and run correctly under any circumstances, you can put these wasm file packages in a static server and then specify the path of the corresponding file in the locateFile parameter.

js
import { createMxCad } from "mxcad";
// Putting both 2d and 2d-st in static resources ensures normal operation regardless of whether SharedArrayBuffer is enabled.
const mode = "SharedArrayBuffer" in window ? "2d" : "2d-st";
createMxCad({
    // ...
    locateFile: (fileName) => {
        new URL(`/node_modules/mxcad/dist/wasm/${mode}/${fileName}`, import.meta.url).href;
    },
});

Most front-end applications are built on bundling tools. The above is a simple explanation of using mxcad in a front-end application built with Vite.

When using mxcad in these front-end applications based on bundling tools, as long as you understand the following principles, you can use mxcad in any bundling tool:

  1. The core of mxcad depends on the files in the /mxcad/dist/wasm directory of the dependency package, corresponding to the classification (2d|2d-st|3d). To ensure that the return value of locateFile can correctly return the path of the corresponding file in the wasm directory (fontspath, fileUrl, including the return value of locateFile must be a network path). In other words, the network address returned by locateFile must be able to access the corresponding file in the browser. Since the wasm directory is in the dependency package of mxcad, all bundling tools should copy the wasm directory to the corresponding static resource directory. Then, locateFile returns the correct network path. You can choose to copy manually or use the bundling tool to copy, depending on the specific operation. Refer to the documentation of the bundling tool for details.

  2. To display text in the drawing correctly, you must load the corresponding font file. The fontspath parameter is the network path of the directory where the font files are stored. In the mxcad dependency package, a default dist/fonts font directory is provided. This directory also needs to be copied to the static resource directory. You can also add various font files needed for your own drawings in this directory.

  3. For performance reasons, mxcad defaults to enabling SharedArrayBuffer to support multi-threading. You need to add the corresponding configuration in the response header of the server (as mentioned above). If you do not want to enable SharedArrayBuffer, then in the address returned by locateFile, choose the file in the /wasm/2d-st/ directory to use 2d-st to enable SharedArrayBuffer and support multi-threading.

Finally, if you are not familiar with front-end bundling tools, it is recommended to first familiarize yourself with the use of bundling tools (webpack|vite).

The following will explain how to use mxcad in different bundling tools and how to configure different bundling tools to make it easier

for you to understand the above principles.

Most front-end application builds currently depend on NodeJS. Please install NodeJS environment before continuing to read if it is not already installed.

If you are familiar with bundling tools, you can click directly to Example Reference to view the source code of using mxcad with corresponding bundling tools to quickly understand the usage.

Using mxcad in Vite

Reference example source code: https://gitee.com/mxcadx/mxcad_docs/tree/master/examples/vite

  1. Install Vite and mxcad:

TIP

If you install using pnpm, you need to install pnpm install mxdraw actively.

sh
npm install vite -D
npm install mxcad
  1. Create a new project root directory and add an HTML file inside:
html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>vite use mxcad</title>
</head>
<body>
    <div style="height: 600px; overflow: hidden;"> <canvas id="myCanvas"></canvas></div>
    <script type="module" src="./src/index.ts"></script>
</body>
</html>
  1. In the root directory, create an src directory and add an index.ts file inside it (Vite defaults to TypeScript). The code is as follows:
ts
import { createMxCad } from "mxcad"
import { MxFun } from "mxdraw"

createMxCad({
    canvas: "#myCanvas",
    locateFile: (fileName) => new URL(`/node_modules/mxcad/dist/wasm/2d/${fileName}`, import.meta.url).href,
    fileUrl: new URL("../assets/test.mxweb", import.meta.url).href,
    fontspath: new URL("node_modules/mxcad/dist/fonts", import.meta.url).href,
})
  1. In the src directory, create an assets folder and (download an mxweb file here). Rename the downloaded file to test.mxweb and copy it to the assets directory.

  2. In the root directory, create a vite.config.ts file:

ts
import { defineConfig } from "vite"

export default defineConfig({
    server: {
        headers: {
          "Cross-Origin-Opener-Policy": "same-origin",
          "Cross-Origin-Embedder-Policy": "require-corp",
        }
    }
})
  1. After completing the above steps, run the following command in the root directory:
sh
npx vite

Using mxcad in webpack

Reference example source code:

https://gitee.com/mxcadx/mxcad_docs/tree/master/examples/webpack-v4

https://gitee.com/mxcadx/mxcad_docs/tree/master/examples/webpack-v5

  1. Installation
sh
npm install webpack webpack-cli copy-webpack-plugin@5 -D
  1. Create a webpack.config.js file in the root directory
js
const path = require('path');
// Ensure compatibility with both webpack 4 and 5 versions for copy-webpack-plugin@5
const CopyWebpackPlugin = require("copy-webpack-plugin");

module.exports = {
  mode: process.env.development === "development" ? "development" : "production",
  entry: './src/index.js',
  devServer: {
    static: './dist',
    headers: {
      "Cross-Origin-Opener-Policy": "same-origin",
      "Cross-Origin-Embedder-Policy": "require-corp"
    }
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.js',
  },
  plugins: [
    new CopyWebpackPlugin([
      // Copy the core mxcad wasm-related code; mxcad defaults to the /* path, so files need to be placed under dist2d
      {
        from: "node_modules/mxcad/dist/wasm/2d/*",
        to: path.resolve(__dirname, "dist"),
        flatten: true
      },
      // Fonts are required to display text in the drawings; mxcad library defaults to the /fonts/* path, so they need to be placed under dist/fonts
      {
        from: "node_modules/mxcad/dist/fonts",
        to: path.resolve(__dirname, "dist/fonts"),
        flatten: true,
        toType: "dir"
      },
    ])
  ],
  // The bundled JS code of mxcad and mxdraw libraries exceeds the default webpack size limit, so set hints: false to disable the warning
  performance: {
    hints: false,
  }
};
  1. Create a new index.html file in the root directory
html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Getting Started</title>
    <script src="https://unpkg.com/lodash@4.17.20"></script>
  </head>
  <body>
     <div style="height: 600px; overflow: hidden;"> <canvas id="myCanvas"></canvas></div>
    <script src="./src/index.js"></script>
  </body>
</html>
  1. Create a new src directory in the root directory and create an index.js file inside the src directory
js
createMxCad({
    canvas: "#myCanvas",
    // Obtain the corresponding file by accessing: http:xxx.com/test.mxweb
    // Please provide this file yourself
    fileUrl: "test.mxweb"
})
  1. After completing the above steps, run the command npx webpack serve to view the result.

Using mxcad directly in HTML

While we have been discussing how front-end applications based on front-end frameworks or bundling tools can utilize mxcad, sometimes we just want to use mxcad simply with HTML and JS.

In mxcad, we provide two ways to use mxcad: CDN and NPM. We've covered the NPM approach earlier, and now let's explore how to load and use mxcad through CDN.

Here, we're using unpkg, but you can also use any CDN that provides npm package services. Alternatively, you can download the files and host the service yourself.

Note

If you directly open the above index.html in the browser, you'll encounter an error. To display the page, you need to start a node service. You can refer to this Node.js code for implementation details.

Using the Global Build Version

Refer to the example source code: index.html

html
<script src="https://unpkg.com/mxdraw/dist/mxdraw.umd.js" crossorigin="anonymous"></script>
<script src="https://unpkg.com/mxcad/dist/mxcad.umd.js" crossorigin="anonymous"></script>
<script>
    const { MxFun } = Mx
    const { createMxCad } = mxcad
    window.onload = function() {
        createMxCad({
            canvas: "#myCanvas",
            locateFile(fileName) {
                return "https://unpkg.com/mxcad/dist/wasm/2d-st/" + fileName
            },
            fileUrl: "test.mxweb"
        })
    }
</script>

Using ES Module Build Version

Refer to the example source code: es.html

Since mxcad depends on the mxdraw library, import an Import Map is necessary to inform the browser how to locate the imported mxdraw and mxcad modules.

You can also add other dependencies to the import map, but make sure you are using the ES module version of the library.

TIP

Import Maps is a relatively new browser feature, so make sure you are using a browser that supports it. Note that only Safari version 16.4 and above supports it.

html
<div style="height: 600px; overflow: hidden;"> <canvas id="myCanvas" style="height: 300px"></canvas></div>
<script type="importmap">
    {
      "imports": {
        "mxdraw": "https://unpkg.com/mxdraw/dist/mxdraw.esm.js",
        "mxcad": "https://unpkg.com/mxcad/dist/mxcad.es.js"
      }
    }
</script>
<script type="module">
    import { MxFun, loadCoreCode } from "mxdraw"
    import { createMxCad } from "mxcad"

    window.onload = function() {
        createMxCad({
            canvas: "#myCanvas",
            locateFile: (fileName)=> "https://unpkg.com/mxcad/dist/wasm/2d-st/" + fileName,
            fontspath: "https://unpkg.com/mxcad/dist/fonts/",
            fileUrl: "/test2.mxweb"
        })
    }
</script>

Example Reference

View examples in Git: GitHub | Gitee

Alternatively, execute the following commands to view all examples, using the Vite directory as an example:

sh
git clone https://github.com/mxcad/mxcad_docs
cd mxcad_docs
cd examples
cd vite
npm install
npm run dev

For other examples, navigate to the corresponding directory:

sh
cd your_example_directory
npm install
npm run dev

TIP

Note that the "examples/public" directory contains shared static resources for all examples. If you copy an example directory to another location, modify the paths of the static resources in the code accordingly.

For instance, in the "webpack-v4" or "webpack-v5" directory, in the "webpack.config.js" file, there is a configuration for moving the test MXWeb file used in development mode:

js
plugins: [
    new CopyWebpackPlugin([
        {
            from: "../public/test2.mxweb",
            to: path.resolve(__dirname, "dist"),
            flatten: true
        }
    ]),
],

In the "vite" directory, the "src/index.ts" file specifies the paths for the MXWeb file and font files:

ts
createMxCad({
    fileUrl: new URL("../../public/test2.mxweb", import.meta.url).href,
    fontspath: new URL("../../public/fonts", import.meta.url).href,
})

Explore how to use the mxcad library in different bundlers or scenarios through examples.

You can also modify and run the code online to see the effects in the Playground.

Below are the translations for the provided Chinese article:


All the examples above are just the simplest projects using the mxcad library and do not implement the relevant functions in CAD through various methods provided by mxcad.

Front-end Application Project for Online Browsing and Editing of CAD Drawings

To meet the needs of different users, mxcad provides a complete front-end application project for online browsing and editing of CAD drawings, incorporating various functions using the APIs provided by mxcad.

You can refer to the implementation of various functions based on the project source code we provide or directly include it using the <iframe> tag.

Front-end source code download link: https://demo.mxdraw3d.com:3562/MxCADCode.7z

Browse version preview link: https://www.mxdraw3d.com/sample/vuebrowse

Edit version preview link: https://demo.mxdraw3d.com:3000/mxcad

Below is the complete documentation for the browse version. For the edit version, please directly jump to Example Project Secondary Development for complete instructions.

Directory address corresponding to MxCADCode.7z after extraction: \Browse\2d\Browse Browse version source code

The simplest way is, of course, through <iframe>. The corresponding way to integrate the browse version front-end page in \Browse\2d\Browseiframe directory is using <iframe>.

The specific steps to start these two projects are as follows:

sh
# Enter the directory after extracting MxCADCode.7z
cd MxCADCode
cd Browse/2d/Browse
npm install
npm run serve
# Open another command line, enter the directory after extracting MxCADCode.7z
cd MxCADCode
cd Browse/2d/Browseiframe
npm install
npm run serve

Finally, visit http://localhost:8051/?debug=true

If you are a front-end developer, you can also directly refer to the source code in \Browse\2d\Browse and implement the required functionality using mxdraw.

Below is an explanation of how to find the corresponding implementation in the source code through the functional buttons on the page:

Run the project and open the website http://localhost:8089/. Open the developer tools (press F12).

Click any button in the menu bar, and the console will print a line of characters, which is the command corresponding to that function.

Open the editor (VsCode), open the \Browse\2d\Browse project, then search for the command, and you can find similar code like this:

js
// The implementation inside the second parameter function is the corresponding implementation of the button function
MxFun.addCommand("command string you searched for", () => {});

Mxcad renders through mxdraw, and the front-end project of this browse version only reads mxweb files through mxcad.

To implement various rendering functions, mainly use various graphic drawing classes or methods provided by mxdraw to implement annotation and other browse-related functions.

These graphic data will not be saved to mxweb files and, more importantly, will not be saved to the drawing.

If you want to save this graphic data to the drawing, please refer to https://help.mxdraw.com/?pid=115 for more information.

Playground

Note

Loading from GitHub might be slow due to network issues; please be patient. Click on elements to select them, click on the operation folder to change the shape. Press the mouse wheel and move the mouse to drag the drawing. Scroll the mouse wheel to zoom in and out. Press the Esc key to deselect all.