Method and device for exporting front-end chart as PNG picture
By designing the drop-down menu and using the state management library to track the status, combined with the Promise chain call and the use of third-party libraries, the problem of difficulty in resolution, data update and editing and modification when exporting front-end charts as PNG pictures is solved, achieving efficient Convenient chart export and user experience improvement.
Patent Information
- Application Number
- CN202411465434.9
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-10-21
- Publication Date
- 2025-02-11
AI Technical Summary
The prior art has resolution and scaling problems, data update difficulties, and editing and modification difficulties when exporting front-end charts as PNG images.
Receive external configuration information through preset input parameters, design the drop-down menu to provide PNG image format export function, use the state management library to track the drop-down menu status, write a callback function to check the chart loading status, and ensure that the browser completes the drawing action through a chain call of Promise. Export, use a third-party library to parse the HTML structure and style rules of the chart area into Canvas objects, and convert them into a standard PNG format image file.
It solves the problems of image quality reduction, data inconsistency and difficulty in modifying, realizes efficient chart export, supports high-resolution display and dynamic data updates, and improves the convenience of user experience and data visualization.
Smart Images

Figure CN119415003A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the field of data processing technology, and in particular to a method, device and electronic device for exporting a front-end chart into a PNG image. Background Art
[0002] Exporting a chart as a PNG image on the front end means that the chart displayed on the page is converted into a PNG format image file programmatically in the web application, and the user is allowed to download or save the image. In this process, it is necessary to determine the HTML element where the chart to be exported is located. Make sure that the style and layout of the selected element and all its child elements are captured correctly. This includes CSS styles, fonts, colors, margins, etc.
[0003] The existing technology has the following problems when exporting front-end charts to PNG images:
[0004] 1. Resolution and scaling issues: PNG is a pixel-based format. When users need to view or print these charts on a larger display, the image quality may degrade and appear pixelated or blurry.
[0005] 2. Difficulty in updating data: If the underlying data changes, the entire PNG image needs to be regenerated. This makes it difficult to maintain consistency across multiple related charts.
[0006] 3. Difficulty in editing and modification: Once exported to PNG, any modification to the chart (such as changing the title, adjusting the color, etc.) requires returning to the original tool to regenerate it.
[0007] The above problems become technical problems that need to be solved. Summary of the invention
[0008] In view of this, an embodiment of the present invention provides a method, device and electronic device for exporting a front-end chart as a PNG image, which at least partially solves the problems existing in the prior art.
[0009] In a first aspect, an embodiment of the present invention provides a method for exporting a front-end chart as a PNG image, comprising:
[0010] Receive external configuration information through preset input parameters, including chart loading status indicator, target chart element selection method and custom output file name option. Chart loading status indicator is used to monitor whether the chart has been rendered. The target chart element selection method supports direct use of DOM nodes. Custom output file name allows users to specify the specific name of the final generated file. All input parameters are verified using the strongly typed programming language feature to obtain incoming data in the expected format.
[0011] Based on the modern front-end framework, a drop-down menu is designed and implemented as the operation entry point. The menu provides the function of exporting PNG images. The appearance style and icon display effect are optimized by appropriately customizing the existing controls in the UI component library and combining the overall visual style guide of the application.
[0012] Use the state management library to build a workflow model, track and record the state changes of the drop-down menu, and write a callback function specifically for processing export requests. The callback function checks whether the chart is currently in a fully loaded state. Only when all relevant data is confirmed to be ready will the subsequent operations be performed;
[0013] After the user clicks the export button to trigger the event, the browser completes the ongoing drawing action based on the internal preset time interval through the Promise chain call method;
[0014] A third-party library is selected as the underlying technical support, and the HTML structure in the entire chart area and all the style rules it contains are parsed into a Canvas object, and then converted into a standard PNG format image file. The obtained PNG format image data is encapsulated into a downloadable form, and the browser's built-in download dialog box is automatically started, allowing users to save it directly to the local device for viewing and use.
[0015] According to a specific implementation of an embodiment of the present invention, the receiving of external configuration information by preset input parameters includes:
[0016] Monitor whether the chart has finished rendering through the chart loading status indicator;
[0017] Provides multiple ways to select target charts by accepting HTMLElement objects or string-type CSS selectors;
[0018] Let the user customize the output file name option by setting an optional parameter to provide the desired file name when initializing the component.
[0019] According to a specific implementation of an embodiment of the present invention, the method of using a strongly typed programming language feature to verify all input parameters to obtain incoming data that conforms to an expected format includes:
[0020] Use the static type checking capabilities of your compiler or build tool to catch type mismatches during compilation.
[0021] Use type guards to write conditional statements to ensure that the data processed under a certain condition is indeed of the expected type;
[0022] For cases where null or undefined occurs, set a default value and use a non-empty assertion to indicate that it will not be null or undefined;
[0023] Throws an error or exception when invalid or unexpected input is detected.
[0024] According to a specific implementation of an embodiment of the present invention, based on a modern front-end framework, a drop-down menu is designed and implemented as an operation entry point, including:
[0025] Include at least one PNG export option in the menu item. The menu item can respond to user click events and provide clear state changes when opened and closed.
[0026] Bind event handlers to each menu item so that the corresponding logic is executed when the user selects an option.
[0027] According to a specific implementation of an embodiment of the present invention, the state management library is used to establish a workflow model, and the state change of whether the drop-down menu is currently expanded or not is tracked and recorded, including:
[0028] Define the first action to indicate that the drop-down menu is opened after the user clicks a button or triggers an event, and define the second action to indicate that the drop-down menu is closed after the user clicks an area outside the menu;
[0029] When the first action is received, isDropdownOpen is set to true, and when the second action is received, isDropdownOpen is set to false.
[0030] According to a specific implementation of an embodiment of the present invention, the callback function specially processing the export request is written, and the callback function checks whether the chart is currently in a completely loaded state, and only when it is confirmed that all relevant data are ready will the subsequent operations be performed, including:
[0031] Get the loading status of the chart from the state management library and check whether the loading status of the chart is "completed";
[0032] If the chart has not yet been loaded, provide a prompt to the user to inform them that the export operation cannot be performed.
[0033] According to a specific implementation of an embodiment of the present invention, after the user clicks the export button to trigger the event, the method of chaining the Promise call allows the browser to complete the ongoing drawing action based on an internally set preset time interval, including:
[0034] Use JavaScript's setTimeout function to create a delayed execution operation. setTimeout returns an ID representing the timer.
[0035] Encapsulate setTimeout in a function that returns a Promise. When the timer ends, the Promise is resolved, and the subsequent code continues to execute.
[0036] Use the .then() method to link multiple Promises together to form a chain call. Each .then() callback will be executed after the previous Promise is resolved.
[0037] Add .catch() to the chain to catch and handle possible errors;
[0038] After the user clicks the export button, the Promise chain is started immediately, and it waits for the preset time interval. Once the time interval is over, the next .then() callback in the Promise chain executes the actual export logic.
[0039] According to a specific implementation of an embodiment of the present invention, the third-party library is selected as the underlying technical support, and the HTML structure in the entire chart area and all the style rules contained therein are parsed into a Canvas object, and then converted into a standard PNG format image file, including:
[0040] Use the package manager to install the selected third-party library and obtain the target chart element through the selection method provided by the user;
[0041] Use the API function provided by the third-party library to convert the target DOM element into a Canvas object;
[0042] Once the Canvas object is successfully created, use the toDataURL method in the CanvasAPI to convert it into a data URL in PNG format;
[0043] For the toDataURL method, specify the image quality to control the quality of the output image.
[0044] In a second aspect, an embodiment of the present invention provides a device for exporting a front-end chart as a PNG image, comprising:
[0045] A receiving module receives external configuration information by presetting input parameters, wherein the input parameters include a chart loading status indicator, a target chart element selection method, and a custom output file name option. The chart loading status indicator is used to monitor whether the chart has been rendered. The target chart element selection method supports the direct use of DOM nodes. The custom output file name allows the user to specify the specific name of the final generated file. All input parameters are verified using the strongly typed programming language feature to obtain incoming data that conforms to the expected format.
[0046] Design module, based on the modern front-end framework, designs and implements a drop-down menu as the operation entry point. The menu provides the function of exporting PNG images. By appropriately customizing the existing controls in the UI component library and combining the overall visual style guide of the application, the appearance style and icon display effect are optimized;
[0047] The recording module uses the state management library to build a workflow model, track and record the state changes of the drop-down menu, and write a callback function specifically for processing export requests. The callback function checks whether the chart is currently in a fully loaded state. Only when all relevant data is confirmed to be ready will the subsequent operations be performed;
[0048] The calling module, after the user clicks the export button to trigger the event, uses the Promise chain calling method to allow the browser to complete the ongoing drawing action based on the internal preset time interval;
[0049] The conversion module selects a third-party library as the underlying technical support, parses the HTML structure in the entire chart area and all the style rules it contains into a Canvas object, and then converts it into a standard PNG format image file. The obtained PNG format image data is encapsulated into a downloadable form, and the browser's built-in download dialog box is automatically launched, allowing users to save it directly to the local device for viewing and use.
[0050] In a third aspect, an embodiment of the present invention further provides an electronic device, the electronic device comprising:
[0051] at least one processor; and,
[0052] a memory communicatively connected to the at least one processor; wherein,
[0053] The memory stores instructions that can be executed by the at least one processor, and the instructions are executed by the at least one processor so that the at least one processor can execute the method of exporting the front-end chart as a PNG image in any of the aforementioned first aspects or any of the implementations of the first aspect.
[0054] In a fourth aspect, an embodiment of the present invention further provides a non-transitory computer-readable storage medium, which stores computer instructions, and the computer instructions are used to enable the computer to execute the method of exporting a front-end chart as a PNG image in the aforementioned first aspect or any implementation of the first aspect.
[0055] In the fifth aspect, an embodiment of the present invention further provides a computer program product, which includes a computer program stored on a non-transitory computer-readable storage medium, and the computer program includes program instructions. When the program instructions are executed by a computer, the computer executes the method of exporting a front-end chart as a PNG image in the aforementioned first aspect or any implementation of the first aspect.
[0056] The solution for exporting a front-end chart as a PNG image in an embodiment of the present invention includes: receiving external configuration information through preset input parameters, wherein the input parameters include a chart loading status indicator, a method for selecting target chart elements, and a custom output file name option, wherein the chart loading status indicator is used to monitor whether the chart has been rendered, the method for selecting target chart elements supports direct use of DOM nodes, and the custom output file name allows the user to specify the specific name of the final generated file, and all input parameters are verified using the strongly typed programming language feature to obtain incoming data that conforms to the expected format; based on a modern front-end framework, a drop-down menu is designed and implemented as an operation entry point, and the menu provides a PNG image format export function, and the appearance style and icon display effect are optimized by appropriately customizing and adjusting the existing controls in the UI component library and combining the overall visual style guide of the application; using the state management The library establishes a workflow model, tracks and records the state changes of whether the drop-down menu is currently expanded or not, and writes a callback function specifically for processing export requests. The callback function checks whether the chart is currently in a fully loaded state. Only when all relevant data are confirmed to be ready will the subsequent operations be continued; after the user clicks the export button to trigger the event, the browser is allowed to complete the ongoing drawing action based on the preset time interval set internally through the Promise chain call method; selects a third-party library as the underlying technical support, and parses the HTML structure in the entire chart area and all the style rules contained therein into a Canvas object, and then converts it into a standard PNG format image file, encapsulates the obtained PNG format image data into a downloadable form, and automatically starts the browser's built-in download dialog box, allowing users to directly save it to the local device for viewing and use. The present invention adapts to various types of visualization components through real-time DOM capture and efficient image conversion. Asynchronous processing and custom naming are used to ensure export timeliness and user experience. Supports high-resolution display and dynamic data updates, providing a convenient solution for data visualization. BRIEF DESCRIPTION OF THE DRAWINGS
[0057] In order to more clearly illustrate the technical solutions of the embodiments of the present invention, the drawings required for use in the embodiments will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present invention. For ordinary technicians in this field, other drawings can be obtained based on these drawings without paying creative work.
[0058] Figure 1 A schematic diagram of a method for exporting a front-end chart as a PNG image provided by an embodiment of the present invention;
[0059] Figure 2 A schematic flow chart of another method for exporting a front-end chart as a PNG image provided by an embodiment of the present invention;
[0060] Figure 3 A schematic diagram of the structure of a device for exporting a front-end chart as a PNG image provided by an embodiment of the present invention;
[0061] Figure 4 A schematic diagram of an electronic device provided by an embodiment of the present invention. DETAILED DESCRIPTION
[0062] The embodiments of the present invention are described in detail below with reference to the accompanying drawings.
[0063] The following describes the embodiments of the present disclosure through specific examples, and those skilled in the art can easily understand other advantages and effects of the present disclosure from the contents disclosed in this specification. Obviously, the described embodiments are only a part of the embodiments of the present disclosure, rather than all of the embodiments. The present disclosure can also be implemented or applied through other different specific embodiments, and the details in this specification can also be modified or changed in various ways based on different viewpoints and applications without departing from the spirit of the present disclosure. It should be noted that the following embodiments and features in the embodiments can be combined with each other without conflict. Based on the embodiments in the present disclosure, all other embodiments obtained by ordinary technicians in the field without making creative work are within the scope of protection of the present disclosure.
[0064] It should be noted that various aspects of the embodiments within the scope of the appended claims are described below. It should be apparent that the aspects described herein may be embodied in a wide variety of forms, and any specific structure and / or function described herein is merely illustrative. Based on the present disclosure, it should be understood by those skilled in the art that an aspect described herein may be implemented independently of any other aspect, and two or more of these aspects may be combined in various ways. For example, any number of aspects described herein may be used to implement the device and / or practice the method. In addition, other structures and / or functionalities other than one or more of the aspects described herein may be used to implement this device and / or practice this method.
[0065] It should also be noted that the illustrations provided in the following embodiments are only schematic illustrations of the basic concept of the present disclosure. The drawings only show components related to the present disclosure rather than being drawn according to the number, shape and size of components in actual implementation. In actual implementation, the type, quantity and proportion of each component may be changed arbitrarily, and the component layout may also be more complicated.
[0066] Additionally, in the following description, specific details are provided to facilitate a thorough understanding of the examples. However, it will be understood by those skilled in the art that the aspects described may be practiced without these specific details.
[0067] The embodiment of the present disclosure provides a method for exporting a front-end chart as a PNG image. The method for exporting a front-end chart as a PNG image provided in this embodiment can be performed by a computing device, which can be implemented as software, or as a combination of software and hardware, and the computing device can be integrated in a server, a terminal device, etc.
[0068] See also Figure 1 and Figure 2 The embodiment of the present disclosure provides a method for exporting a front-end chart as a PNG image, including:
[0069] S101, receiving external configuration information through preset input parameters, wherein the input parameters include a chart loading status indicator, a method for selecting target chart elements, and a custom output file name option. The chart loading status indicator is used to monitor whether the chart has been rendered. The method for selecting target chart elements supports directly using DOM nodes. The custom output file name allows the user to specify the specific name of the final generated file. All input parameters are verified using the strongly typed programming language feature to obtain incoming data that conforms to the expected format.
[0070] By presetting input parameters to receive external configuration information, the flexibility and configurability of the chart export component can be ensured, which can include the following steps:
[0071] 1. Define input parameters, including but not limited to:
[0072] Chart loading status indicator (isChartLoaded:boolean): This is a Boolean value used to monitor whether the chart has been rendered. If isChartLoaded is true, it means that the chart has been fully loaded; otherwise, it means that the chart is still loading.
[0073] Target chart element selection method (chartElement: HTMLElement): This parameter allows you to directly pass a DOM node as the target chart element. This allows you to directly specify the chart area to be exported, avoiding complex CSS selectors or additional search steps.
[0074] Custom output file name option (outputFileName: string): Users can use this parameter to specify the specific name of the final generated PNG image file. If no file name is provided, the default naming convention (such as "chart_export.png") can be used.
[0075] 2. Use strongly typed programming language features for verification
[0076] Leverage the type system of a strongly typed programming language such as TypeScript to perform strict type checking on the parameters passed in. For example, isChartLoaded must be a Boolean value, chartElement must be an HTMLElement object, and outputFileName must be a string.
[0077] Set sensible defaults for each parameter. For example, if outputFileName is not provided, you can set a default file name.
[0078] In addition to type checking, the boundary conditions of the parameters also need to be verified. For example, outputFileName cannot be an empty string and must comply with file naming specifications (such as not allowing illegal characters).
[0079] When invalid parameters or parameters that do not conform to the expected format are detected, clear error messages are provided to help developers quickly locate and correct the problem.
[0080] 3. Verification logic
[0081] When the component is initialized, immediately validate all incoming parameters. If any parameter is found not to conform to the expected format, an exception can be thrown or a clear error message can be returned. Before actually performing the export operation, confirm the validity of all parameters again. Especially for dynamically updated states (such as isChartLoaded), ensure that the chart has been fully loaded before performing the export.
[0082] 4. Documentation
[0083] Write detailed API documentation that explains what each parameter does, the supported data types, and their possible default values. Provide sample code snippets that show how to initialize and use the component correctly, and explain the differences in behavior in each case.
[0084] Through the above steps, we can ensure that all input parameters of the chart export component are strictly verified, thereby improving the stability and reliability of the component. This method can not only prevent many common programming errors, but also significantly improve development efficiency and user experience.
[0085] S102, based on a modern front-end framework, designs and implements a drop-down menu as an operation entry point. The menu provides a PNG image format export function. It optimizes the appearance style and icon display effect by appropriately customizing the existing controls in the UI component library and combining the overall visual style guide of the application.
[0086] Based on a modern front-end framework (such as React, Vue, or Angular), design and implement a drop-down menu as the operation entry point of the chart export component, and provide PNG image format export function, which can be achieved by following the steps below:
[0087] 1. Choose the right front-end framework and UI component library
[0088] Front-end framework: Choose a modern front-end framework that suits the needs of your project, such as React, Vue, or Angular.
[0089] UI component library: Choose a UI component library that is compatible with your chosen framework and fits the overall visual style of your app. Common choices include:
[0090] React:Material-UI,AntDesign,ChakraUI
[0091] Vue: Vuetify, ElementUI, Quasar
[0092] Angular:AngularMaterial,PrimeNG,NG-ZORRO
[0093] 2. Design a drop-down menu
[0094] Define the options in the drop-down menu, including at least one "Export to PNG" option. You can add more options as needed, such as "Export to PDF", "Export to SVG", etc. Use intuitive icons to represent different operation options. For example, use the "Download" icon to represent the export function. Make sure the icon is consistent with the overall visual style of the app.
[0095] 3. Customized adjustment controls
[0096] According to the overall visual style guide of the application, make appropriate style adjustments to the existing drop-down menu controls in the UI component library. This may include color schemes, font styles, border styles, etc.
[0097] Make sure your drop-down menus look good on different screen sizes, especially on small mobile screens. Consider responsive design so that your menus look great on different devices.
[0098] Add appropriate animation effects to the drop-down menu, such as transition animations when expanding and collapsing, to enhance the user experience.
[0099] 4. Integrate into the application
[0100] Introduce a custom drop-down menu component into your application. Make sure it can be called and rendered where needed. Bind the corresponding event handlers for each option in the drop-down menu. For example, the "Export to PNG" option should trigger the export function. Use a state management library (such as Redux, Vuex, or NgRx) to track the state changes of the drop-down menu. Make sure that the open and closed states of the menu are correctly reflected in the UI.
[0101] 5. Optimize appearance style and icon display effect
[0102] Make sure the design of the drop-down menu is consistent with the overall visual style of the application. This includes color schemes, font styles, border styles, etc. Use high-quality icon resources and ensure that the icons display well at different resolutions. You can use icon fonts (such as FontAwesome) or SVG icons to improve scalability and clarity. Provide users with clear interaction feedback. For example, change the background color or highlight the icon when the mouse hovers, and have an animated transition effect after clicking.
[0103] Through the above steps, you can design and implement a beautiful and practical drop-down menu based on a modern front-end framework as the operation entry point of the chart export component. This menu can not only improve the user experience, but also enhance the consistency and professionalism of the entire application.
[0104] S103, using the state management library to establish a workflow model, track and record the state changes of the drop-down menu, and write a callback function specifically for processing export requests. The callback function checks whether the chart is currently in a fully loaded state. Only when it is confirmed that all relevant data are ready will the subsequent operations be executed.
[0105] Use the state management library to build a workflow model, track and record the state changes of the drop-down menu, and write a callback function specifically for processing export requests to ensure that the export operation is performed only after the chart is fully loaded. You can follow the steps below:
[0106] 1. Choose a suitable state management library, such as:
[0107] Redux (React): A state management solution for large applications.
[0108] Vuex (Vue): A state management mode designed specifically for Vue.js.
[0109] NgRx (Angular): A state management library for Angular applications based on RxJS.
[0110] MobX (React, Vue, Angular): provides a more intuitive way to manage state.
[0111] 2. Define the state structure
[0112] Define a state object to represent the state of the drop-down menu and the chart. For example:
[0113] isDropdownOpen: Boolean value indicating whether the drop-down menu is open.
[0114] isChartLoaded: Boolean value indicating whether the chart has finished rendering.
[0115] Set a reasonable initial state. For example, isDropdownOpen is false and isChartLoaded is also false in the initial state.
[0116] 3. Define actions
[0117] Open / Close Drop-down Menu: Define actions to control the opening and closing of the drop-down menu.
[0118] OPEN_DROPDOWN: Indicates opening the drop-down menu.
[0119] CLOSE_DROPDOWN: Indicates closing the drop-down menu.
[0120] Chart Loading Status: Define actions to update the loading status of the chart.
[0121] CHART_LOADED: Indicates that the chart has been loaded.
[0122] CHART_LOADING: Indicates that the chart is loading.
[0123] 4. Define state update logic (Reducers / Actions)
[0124] Update the state of the drop-down menu: Update the state of isDropdownOpen according to the type of action received. If an OPEN_DROPDOWN action is received, set isDropdownOpen to true. If a CLOSE_DROPDOWN action is received, set isDropdownOpen to false.
[0125] Updates the state of isChartLoaded depending on the type of action received. If a CHART_LOADED action is received, set isChartLoaded to true. If a CHART_LOADING action is received, set isChartLoaded to false.
[0126] 5. Integrate into the application
[0127] Use the methods provided by the state management library to expose the state object to the entire application. For example, in Redux, the state can be passed to all child components through the Provider component. In components that need to use the state of drop-down menus and charts, access the state through the methods provided by the state management library (such as connect in Redux and observer in MobX). In components, use the methods provided by the state management library (such as dispatch in Redux and actions in MobX) to distribute actions to change the state.
[0128] 6. Write a callback function to handle export requests
[0129] In the callback function, first get the current chart loading status (isChartLoaded) from the state management library. If isChartLoaded is true, it means that the chart has been fully loaded and the export operation can continue. If isChartLoaded is false, provide a friendly prompt to the user to inform them that the export operation cannot be performed at the moment. You can display a warning box or update a status in the UI to tell the user that the chart is still loading and please try again later.
[0130] If the chart is fully loaded, call the actual export logic, such as converting the chart to a PNG image, generating the file, triggering the download, etc.
[0131] Through the above steps, a robust and easy-to-maintain workflow model can be established to effectively track and manage the state changes of the drop-down menu and ensure that the export operation is safely performed after the chart is fully loaded. This not only improves the performance and user experience of the application, but also makes the code more modular and testable.
[0132] S104, after the user clicks the export button to trigger the event, the browser is allowed to complete the ongoing drawing action based on the internally set preset time interval through the Promise chain call method.
[0133] After the user clicks the export button to trigger the event, a preset time interval is set through the Promise chain call to ensure that the browser has enough time to complete all ongoing drawing actions. This method can effectively solve the problem of incomplete or inaccurate chart export caused by rendering timing issues. The following are the detailed steps to achieve this goal:
[0134] 1. Determine the time interval
[0135] You can determine a reasonable time interval based on experience or test results. This time interval should be long enough to ensure that all drawing actions (such as animations, data updates, etc.) can be completed. For example, you can choose a value between 500 milliseconds and 1000 milliseconds.
[0136] 2. Create a Promise Chain
[0137] Use JavaScript's setTimeout function to create a delayed execution operation. setTimeout returns an ID representing the timer, but you can better control the asynchronous process by encapsulating it in a Promise. Encapsulate setTimeout in a function that returns a Promise. When the timer ends, the Promise will be resolved, so that the subsequent code can continue to execute.
[0138] 3. Chaining Promises
[0139] Multiple Promises are linked together through the .then() method to form a chain call. Each .then() callback will be executed after the previous Promise is resolved. You can add .catch() in the chain to capture and handle possible errors.
[0140] 4. Trigger the export operation
[0141] After the user clicks the export button, the Promise chain is started immediately, and it waits for the preset time interval. Once the time interval is over, the next .then() callback in the Promise chain will execute the actual export logic, such as converting the chart to an image, generating a file, triggering a download, etc.
[0142] Through the above steps, it can be ensured that after the user clicks the export button, the browser has enough time to complete all drawing actions and generate a complete chart image. This not only improves the quality of the export, but also improves the user experience.
[0143] S105, select a third-party library as the underlying technical support, parse the HTML structure in the entire chart area and all the style rules it contains into a Canvas object, and then convert it into a standard PNG format image file, encapsulate the obtained PNG format image data into a downloadable form, and automatically start the browser's built-in download dialog box, so that the user can directly save it to the local device for viewing and use.
[0144] A third-party library is selected as the underlying technical support, and the HTML structure in the entire chart area and all the style rules it contains are parsed into a Canvas object, and then converted into a standard PNG format image file, which is packaged into a downloadable form, and the browser's built-in download dialog box is automatically launched, allowing users to directly save it to the local device for viewing and use. The following are the detailed steps to achieve this goal:
[0145] 1. Choose a suitable third-party library, such as:
[0146] html2canvas, a widely used JavaScript library that can render HTML elements (including their styles and contents) as Canvas objects.
[0147] dom-to-image is another powerful library that provides multiple export options, such as PNG, JPEG, SVG, etc., and supports cross-domain resource processing.
[0148] 2. Introducing third-party libraries
[0149] Install the selected third-party library using a package manager such as npm or yarn. For example, for html2canvas, you can run npm install html2canvas. Import the required library in your project to ensure that the library has been correctly loaded and can be used in your code.
[0150] 3. Select the target chart element
[0151] Get the target chart element through the selection method provided by the user (such as DOM node reference or CSS selector) to ensure that the element has been correctly rendered and is visible.
[0152] 4. Call library function for conversion
[0153] Use the API functions provided by third-party libraries (such as the html2canvas function of html2canvas) to convert the target DOM element to a Canvas object. Pass necessary parameters, such as the target element, configuration options, etc. Set the configuration options of the conversion as needed, such as whether to ignore background transparency, whether to include external resources, etc.
[0154] 5. Handling cross-origin resources
[0155] If the chart contains cross-domain images or other resources, you need to set CORS headers on the server side, or use a proxy server to bypass cross-domain restrictions. In some cases, preloading all resources can improve the performance and reliability of the conversion.
[0156] 6. Generate PNG images
[0157] Once the Canvas object is successfully created, you can use the toDataURL method in the CanvasAPI to convert it to a data URL in PNG format. For the toDataURL method, you can specify the quality of the image (for example, toDataURL('image / png',quality)) to control the quality of the output image.
[0158] 7. Package into downloadable form
[0159] Use JavaScript to dynamically create a hidden tag and set its href attribute to the generated data URL. The download attribute of the tag sets the file name of the download. This can be achieved by a user-defined file name or a default file name. The click event of the label launches the browser's download dialog box, allowing the user to save the image to the local device.
[0160] During the conversion and download process, provide visual feedback to the user, such as showing a loading indicator or progress bar, to let the user know that the system is processing their request. When the download is complete, remove the loading indicator and display a success message to inform the user that the file is ready to download. If an error occurs during the conversion or download process, provide the user with detailed error information and suggest how to resolve it.
[0161] Through the above steps, you can use third-party libraries to convert complex HTML charts into high-quality PNG images and provide them to users for download. This not only simplifies development work, but also improves the reliability of the final product and user experience.
[0162] This paper uses an innovative front-end chart export PNG implementation technology. Through real-time DOM capture and efficient image conversion, it adapts to various visualization components. It uses asynchronous processing and custom naming to ensure export timeliness and user experience. It supports high-resolution display and dynamic data update, providing a convenient solution for data visualization.
[0163] See also Figure 2 The main technical solution of the present invention includes the following steps:
[0164] 1) Component configuration: Design a configurable user interface component that receives chart loading status, target element reference, and output file name as input parameters.
[0165] 2) Interface construction: Implement a drop-down menu interface containing PNG export options, ensuring that its design meets the style and usability standards of the overall application.
[0166] 3) Event handling: Develop menu event handling logic to verify chart loading status when the user selects the export option to prevent exporting when the data is incomplete.
[0167] 4) Asynchronous operation: Implement an asynchronous processing mechanism and set a short delay after triggering the export operation to ensure that the latest chart rendering status is captured.
[0168] 5) Image conversion: Use a dedicated DOM to image library to accurately convert the specified chart elements into high-quality PNG format images, preserving complete visual details.
[0169] 6) File Download: Develop a generic file download function that properly handles the generated image data, sets the appropriate file type and name, and initiates the browser download process.
[0170] 7) Exception handling: Implement a comprehensive error capture and handling mechanism, covering the entire process from image generation to downloading, providing clear error feedback to ensure user experience.
[0171] Specifically, they include:
[0172] Component design and parameter configuration:
[0173] • Design a flexible chart export component with a clear definition of the input parameter mechanism. These parameters include a chart loading status indicator, a reference method for the target chart element, and an option to allow custom output file names. A type-safe approach is used to ensure the stability and reusability of the component.
[0174] Interactive interface construction:
[0175] •Build an intuitive user interface, mainly consisting of a drop-down menu. The menu provides export options in PNG format, and through a carefully designed style and icon system, ensures consistency with the overall application's visual style to enhance the user experience.
[0176] User operation response mechanism:
[0177] • Implement an accurate state management system to monitor the expansion status of the drop-down menu. Develop a dedicated function to handle user export requests. This function can intelligently determine the loading status of the current chart to prevent export operations when the data is incomplete.
[0178] Asynchronous processing strategy:
[0179] •Use micro-task scheduling technology to set a short time delay after the user triggers the export. This method cleverly solves potential rendering timing issues and ensures that all chart elements are fully rendered and updated when taking a chart snapshot.
[0180] Converting graphs to images:
[0181] •Integrate professional Document Object Model (DOM) to image technology to achieve accurate conversion from complex chart structures to high-quality PNG images. This process includes handling possible cross-domain resource issues to ensure that the generated image fully replicates the visual effects of the original chart, including all details and styles.
[0182] File generation and download implementation:
[0183] • Develop a general file handling system that can convert the generated image data into a downloadable format. This system is responsible for setting the correct file type, handling the file naming logic, and emulating user download behavior, seamlessly integrating into the browser's standard download mechanism.
[0184] Robust error handling system:
[0185] • Implement a comprehensive error capture and handling strategy that covers the entire process from image generation to file download. This system can capture a variety of potential abnormal situations, record detailed error information, and provide key data for development debugging and problem diagnosis in production environments.
[0186] According to a specific implementation of an embodiment of the present invention, the receiving of external configuration information by preset input parameters includes:
[0187] Monitor whether the chart has finished rendering through the chart loading status indicator;
[0188] Provides multiple ways to select target charts by accepting HTMLElement objects or string-type CSS selectors;
[0189] Let the user customize the output file name option by setting an optional parameter to provide the desired file name when initializing the component.
[0190] According to a specific implementation of an embodiment of the present invention, the method of using a strongly typed programming language feature to verify all input parameters to obtain incoming data that conforms to an expected format includes:
[0191] Use the static type checking capabilities of your compiler or build tool to catch type mismatches during compilation.
[0192] Use type guards to write conditional statements to ensure that the data processed under a certain condition is indeed of the expected type;
[0193] For cases where null or undefined occurs, set a default value and use a non-empty assertion to indicate that it will not be null or undefined;
[0194] Throws an error or exception when invalid or unexpected input is detected.
[0195] According to a specific implementation of an embodiment of the present invention, based on a modern front-end framework, a drop-down menu is designed and implemented as an operation entry point, including:
[0196] Include at least one PNG export option in the menu item. The menu item can respond to user click events and provide clear state changes when opened and closed.
[0197] Bind event handlers to each menu item so that the corresponding logic is executed when the user selects an option.
[0198] According to a specific implementation of an embodiment of the present invention, the state management library is used to establish a workflow model, and the state change of whether the drop-down menu is currently expanded or not is tracked and recorded, including:
[0199] Define the first action to indicate that the drop-down menu is opened after the user clicks a button or triggers an event, and define the second action to indicate that the drop-down menu is closed after the user clicks an area outside the menu;
[0200] When the first action is received, isDropdownOpen is set to true, and when the second action is received, isDropdownOpen is set to false.
[0201] According to a specific implementation of an embodiment of the present invention, the callback function specially processing the export request is written, and the callback function checks whether the chart is currently in a completely loaded state, and only when it is confirmed that all relevant data are ready will the subsequent operations be performed, including:
[0202] Get the loading status of the chart from the state management library and check whether the loading status of the chart is "completed";
[0203] If the chart has not yet been loaded, provide a prompt to the user to inform them that the export operation cannot be performed.
[0204] According to a specific implementation of an embodiment of the present invention, after the user clicks the export button to trigger the event, the method of chaining the Promise call allows the browser to complete the ongoing drawing action based on an internally set preset time interval, including:
[0205] Use JavaScript's setTimeout function to create a delayed execution operation. setTimeout returns an ID representing the timer.
[0206] Encapsulate setTimeout in a function that returns a Promise. When the timer ends, the Promise is resolved, and the subsequent code continues to execute.
[0207] Use the .then() method to link multiple Promises together to form a chain call. Each .then() callback will be executed after the previous Promise is resolved.
[0208] Add .catch() to the chain to catch and handle possible errors;
[0209] After the user clicks the export button, the Promise chain is started immediately, and it waits for the preset time interval. Once the time interval is over, the next .then() callback in the Promise chain executes the actual export logic.
[0210] According to a specific implementation of an embodiment of the present invention, the third-party library is selected as the underlying technical support, and the HTML structure in the entire chart area and all the style rules contained therein are parsed into a Canvas object, and then converted into a standard PNG format image file, including:
[0211] Use the package manager to install the selected third-party library and obtain the target chart element through the selection method provided by the user;
[0212] Use the API function provided by the third-party library to convert the target DOM element into a Canvas object;
[0213] Once the Canvas object is successfully created, use the toDataURL method in the CanvasAPI to convert it into a data URL in PNG format;
[0214] For the toDataURL method, specify the image quality to control the quality of the output image.
[0215] Corresponding to the above method embodiment, see Figure 3 The embodiment of the present invention further discloses a device 30 for exporting a front-end chart as a PNG image, comprising:
[0216] The receiving module 301 receives external configuration information by presetting input parameters, wherein the input parameters include a chart loading status indicator, a target chart element selection method, and a custom output file name option. The chart loading status indicator is used to monitor whether the chart has been rendered. The target chart element selection method supports directly using DOM nodes. The custom output file name allows the user to specify the specific name of the final generated file. All input parameters are verified using the strongly typed programming language feature to obtain incoming data that conforms to the expected format.
[0217] Design module 302, based on a modern front-end framework, designs and implements a drop-down menu as an operation entry point, which provides a PNG image format export function, optimizes the appearance style and icon display effect by appropriately customizing the existing controls in the UI component library and combining the overall visual style guide of the application;
[0218] Recording module 303, using the state management library to establish a workflow model, track and record the state changes of the drop-down menu, and write a callback function specifically for processing export requests. The callback function checks whether the chart is currently in a fully loaded state. Only when it is confirmed that all relevant data are ready will the subsequent operations be continued;
[0219] Calling module 304, after the user clicks the export button to trigger the event, through the Promise chain calling method, based on the internal preset time interval, allows the browser to complete the ongoing drawing action;
[0220] The conversion module 305 selects a third-party library as the underlying technical support, parses the HTML structure in the entire chart area and all the style rules it contains into a Canvas object, and then converts it into a standard PNG format image file, encapsulates the obtained PNG format image data into a downloadable form, and automatically starts the browser's built-in download dialog box, allowing the user to directly save it to the local device for viewing and use.
[0221] See also Figure 4 The embodiment of the present invention further provides an electronic device 60, the electronic device comprising:
[0222] at least one processor; and,
[0223] a memory communicatively connected to the at least one processor; wherein,
[0224] The memory stores instructions that can be executed by the at least one processor, and the instructions are executed by the at least one processor so that the at least one processor can execute the method of exporting the front-end chart as a PNG image in the aforementioned method embodiment.
[0225] An embodiment of the present invention further provides a non-transitory computer-readable storage medium, which stores computer instructions, and the computer instructions are used to enable the computer to execute the aforementioned method embodiment.
[0226] An embodiment of the present invention also provides a computer program product, which includes a computer program stored on a non-transitory computer-readable storage medium. The computer program includes program instructions. When the program instructions are executed by a computer, the computer executes the method of exporting a front-end chart as a PNG image in the aforementioned method embodiment.
[0227] Reference below Figure 4 , which shows a schematic diagram of the structure of an electronic device 60 suitable for implementing the embodiment of the present disclosure. The electronic device in the embodiment of the present disclosure may include, but is not limited to, mobile terminals such as mobile phones, notebook computers, digital broadcast receivers, PDAs (personal digital assistants), PADs (tablet computers), PMPs (portable multimedia players), vehicle terminals (such as vehicle navigation terminals), etc., and fixed terminals such as digital TVs, desktop computers, etc. Figure 4 The electronic device shown is only an example and should not bring any limitation to the functions and scope of use of the embodiments of the present disclosure.
[0228] like Figure 4 As shown, the electronic device 60 may include a processing device (e.g., a central processing unit, a graphics processing unit, etc.) 601, which can perform various appropriate actions and processes according to a program stored in a read-only memory (ROM) 602 or a program loaded from a storage device 608 into a random access memory (RAM) 603. In the RAM 603, various programs and data required for the operation of the electronic device 60 are also stored. The processing device 601, the ROM 602, and the RAM 603 are connected to each other via a bus 604. An input / output (I / O) interface 605 is also connected to the bus 604.
[0229] Typically, the following devices may be connected to the I / O interface 605: an input device 606 including, for example, a touch screen, a touch pad, a keyboard, a mouse, an image sensor, a microphone, a gage, a gyroscope, etc.; an output device 607 including, for example, a liquid crystal display (LCD), a speaker, a vibrator, etc.; a storage device 608 including, for example, a magnetic tape, a hard disk, etc.; and a communication device 609. The communication device 609 may allow the electronic device 60 to communicate with other devices wirelessly or by wire to exchange data. Although Figure 4 The electronic device 60 is shown with various devices, but it should be understood that it is not required to implement or have all the devices shown. More or fewer devices may be implemented or have instead.
[0230] In particular, according to an embodiment of the present disclosure, the process described above with reference to the flowchart can be implemented as a computer software program. For example, an embodiment of the present disclosure includes a computer program product, which includes a computer program carried on a computer-readable medium, and the computer program includes a program code for executing the method shown in the flowchart. In such an embodiment, the computer program can be downloaded and installed from a network through a communication device 609, or installed from a storage device 608, or installed from a ROM 602. When the computer program is executed by the processing device 601, the above-mentioned functions defined in the method of the embodiment of the present disclosure are executed.
[0231] The above is only a specific embodiment of the present invention, but the protection scope of the present invention is not limited thereto. Any changes or substitutions that can be easily thought of by a person skilled in the art within the technical scope disclosed by the present invention should be included in the protection scope of the present invention. Therefore, the protection scope of the present invention shall be subject to the protection scope of the claims.
Claims
1. A method for exporting a front-end chart as a PNG image, characterized in that: include: Receive external configuration information through preset input parameters, including chart loading status indicator, target chart element selection method and custom output file name option. Chart loading status indicator is used to monitor whether the chart has been rendered. The target chart element selection method supports direct use of DOM nodes. Custom output file name allows users to specify the specific name of the final generated file. All input parameters are verified using the strongly typed programming language feature to obtain incoming data in the expected format. Based on the modern front-end framework, a drop-down menu is designed and implemented as the operation entry point. The menu provides the function of exporting PNG images. The appearance style and icon display effect are optimized by appropriately customizing the existing controls in the UI component library and combining the overall visual style guide of the application. Use the state management library to build a workflow model, track and record the state changes of the drop-down menu, and write a callback function specifically for processing export requests. The callback function checks whether the chart is currently in a fully loaded state. Only when all relevant data is confirmed to be ready will the subsequent operations be performed; After the user clicks the export button to trigger the event, the browser completes the ongoing drawing action based on the internal preset time interval through the Promise chain call method; A third-party library is selected as the underlying technical support, and the HTML structure in the entire chart area and all the style rules it contains are parsed into a Canvas object, and then converted into a standard PNG format image file. The obtained PNG format image data is encapsulated into a downloadable form, and the browser's built-in download dialog box is automatically started, allowing users to save it directly to the local device for viewing and use.
2. The method according to claim 1, characterized in that: The receiving of external configuration information by preset input parameters includes: Monitor whether the chart has finished rendering through the chart loading status indicator; Provides multiple ways to select target charts by accepting HTMLElement objects or string-type CSS selectors; Let the user customize the output file name option by setting an optional parameter to provide the desired file name when initializing the component.
3. The method according to claim 2, characterized in that The strong type programming language feature is used to verify all input parameters to obtain incoming data that conforms to the expected format, including: Use the static type checking capabilities of your compiler or build tool to catch type mismatches during compilation. Use type guards to write conditional statements to ensure that the data processed under a certain condition is indeed of the expected type; For cases where null or undefined occurs, set a default value and use a non-empty assertion to indicate that it will not be null or undefined; Throws an error or exception when invalid or unexpected input is detected.
4. The method according to claim 3, characterized in that Based on the modern front-end framework, a drop-down menu is designed and implemented as the operation entry point, including: Include at least one PNG export option in the menu item. The menu item can respond to user click events and provide clear state changes when opened and closed. Bind event handlers to each menu item so that the corresponding logic is executed when the user selects an option.
5. The method according to claim 4, characterized in that The state management library is used to establish a workflow model to track and record the state change of whether the drop-down menu is currently expanded or not, including: Define the first action to indicate that the drop-down menu is opened after the user clicks a button or triggers an event, and define the second action to indicate that the drop-down menu is closed after the user clicks an area outside the menu; When the first action is received, isDropdownOpen is set to true, and when the second action is received, isDropdownOpen is set to false.
6. The method according to claim 5, characterized in that The callback function specifically for processing export requests is written. The callback function checks whether the chart is currently fully loaded. Only when all relevant data is confirmed to be ready will the subsequent operations be performed, including: Get the loading status of the chart from the status management library and check whether the loading status of the chart is "completed"; If the chart has not yet been loaded, provide a prompt to the user to inform them that the export operation cannot be performed.
7. The method according to claim 6, characterized in that After the user clicks the export button to trigger the event, the browser completes the ongoing drawing action based on the internal preset time interval through the Promise chain call method, including: Use JavaScript's setTimeout function to create a delayed execution operation. setTimeout returns an ID representing the timer. Encapsulate setTimeout in a function that returns a Promise. When the timer ends, the Promise is resolved, and the subsequent code continues to execute. Use the .then() method to link multiple Promises together to form a chain call. Each .then() callback will be executed after the previous Promise is resolved. Add .catch() to the chain to catch and handle possible errors; After the user clicks the export button, the Promise chain is started immediately, and it waits for the preset time interval. Once the time interval is over, the next .then() callback in the Promise chain executes the actual export logic.
8. The method according to claim 7, characterized in that The third-party library is selected as the underlying technical support, and the HTML structure in the entire chart area and all the style rules contained therein are parsed into a Canvas object, and then converted into a standard PNG format image file, including: Use the package manager to install the selected third-party library and obtain the target chart element through the selection method provided by the user; Use the API function provided by the third-party library to convert the target DOM element into a Canvas object; Once the Canvas object is successfully created, use the toDataURL method in the CanvasAPI to convert it into a data URL in PNG format; For the toDataURL method, specify the image quality to control the quality of the output image.
9. A device for exporting a front-end chart as a PNG picture, characterized in that: include: A receiving module receives external configuration information by presetting input parameters, wherein the input parameters include a chart loading status indicator, a target chart element selection method, and a custom output file name option. The chart loading status indicator is used to monitor whether the chart has been rendered. The target chart element selection method supports the direct use of DOM nodes. The custom output file name allows the user to specify the specific name of the final generated file. All input parameters are verified using the strongly typed programming language feature to obtain incoming data that conforms to the expected format. Design module, based on the modern front-end framework, designs and implements a drop-down menu as the operation entry point. The menu provides the function of exporting PNG images. By appropriately customizing the existing controls in the UI component library and combining the overall visual style guide of the application, the appearance style and icon display effect are optimized; The recording module uses the state management library to build a workflow model, track and record the state changes of the drop-down menu, and write a callback function specifically for processing export requests. The callback function checks whether the chart is currently in a fully loaded state. Only when all relevant data is confirmed to be ready will the subsequent operations be performed; The calling module, after the user clicks the export button to trigger the event, uses the Promise chain calling method to allow the browser to complete the ongoing drawing action based on the internal preset time interval; The conversion module selects a third-party library as the underlying technical support, parses the HTML structure in the entire chart area and all the style rules it contains into a Canvas object, and then converts it into a standard PNG format image file. The obtained PNG format image data is encapsulated into a downloadable form, and the browser's built-in download dialog box is automatically launched, allowing users to save it directly to the local device for viewing and use.
10. An electronic device, characterized in that: The electronic device comprises: at least one processor; and, a memory communicatively connected to the at least one processor; wherein, The memory stores instructions executable by the at least one processor, and the instructions are executed by the at least one processor to enable the at least one processor to execute the method of exporting a front-end chart as a PNG image as described in any one of claims 1 to 8.