HTML5: The cornerstone of modern networks. Today, SVG and Canvas are often the technology of choice when creating interactive images—Flash has been forgotten, Silverlight has become a rare unicorn at the edge of the network, and few people remember third-party plugins.
The pros and cons of each technique are well documented, but in short, SVG is better suited to creating and handling interactive elements. This is because SVG is an XML-based vector format that when an image is loaded into a page using the <svg></svg>
tag, each element in it can be used in the SVG DOM.
In this article, I want to introduce you to GraphicsJS, a new and powerful open source JavaScript drawing library based on SVG (for older IE versions, it has a VML alternative). I'll start by quickly introducing its basics and then showcase the library's capabilities with two short and wonderful examples: the first example is entirely about art, and the second example shows how to write a simple one in less than 50 lines of code Puzzle art game.
There are many libraries that help developers use SVG: Raphaël, Snap.svg, and BonsaiJS, to name just a few of the best libraries. These libraries each have their pros and cons, but a thorough comparison of them will be the subject of another article. This article is about GraphicsJS, so let me explain what it has and what it has.
First of all, GraphicsJS is lightweight and has a very flexible JavaScript API. It implements many rich text features, as well as a virtual DOM separate from browser-specific HTML DOM implementations.
Secondly, it is a new open source JavaScript library released last fall by AnyChart, one of the world's leading interactive data visualization software developers. AnyChart has been using GraphicsJS for at least three years (since the release of AnyChart 7.0) to render charts in its proprietary products, so GraphicsJS is fully combat-tested. (Disclaimer: I am the Head of R&D at AnyChart and the Lead Developer at GraphicsJS)
Third, unlike AnyChart's JavaScript drawing library, GraphicsJS is available for free for commercial and nonprofit projects. It is available on GitHub under the Apache license.
Fourth, GraphicsJS has cross-browser compatibility and supports Internet Explorer 6.0, Safari 3.0, Firefox 3.0, and Opera 9.5. It is rendered in VML in older IE versions and in SVG in all other browsers.
Lastly, GraphicsJS allows you to combine graphics and animations perfectly. Check out its main gallery, including animated bonfires, spinning galaxies, rainfall, procedurally generated leaves, playable 15 puzzle games and more. GraphicsJS contains more examples in its detailed documentation and comprehensive API reference.
To get started with GraphicsJS, you need to reference the library and create a block-level HTML element for the drawing:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>GraphicsJS Basic Example</title> </head> <body> <div id="stage-container" style="width: 400px; height: 375px;"></div> <🎜> <🎜> </body> </html>
You should then create a stage and draw something in it, such as a rectangle, circle, or other shape:
// 创建舞台 var stage = acgraph.create('stage-container'); // 绘制矩形 var stage.rect(25, 50, 350, 300);
The following is an example on CodePen where we go a step further and draw the Deathly Hallows symbol.
Any shape or path can be colored using fill settings and stroke settings. Everything has a stroke (border), but only the shape and closed paths have padding. Fill and stroke settings are very rich, and you can use linear or circular gradients for fill and stroke. Additionally, the lines may be dotted and support image fills with multiple tile modes. But this is all pretty standard stuff you can find in almost any library. What makes GraphicsJS special is its mesh and pattern fill feature, which not only allows you to use 32 (!) of available mesh fill patterns directly, but also allows you to easily create custom patterns made of shapes or text.
Now, let's see what exactly can be achieved! I will draw a simple drawing of a man standing near the house and fill it with different patterns and colors to enhance it. For simplicity, let's make it a childish art painting (and try not to involve art roughness). That's it:
// 创建舞台 var stage = acgraph.create('stage-container'); // 绘制框架 var frame = stage.rect(25, 50, 350, 300); // 绘制房子 var walls = stage.rect(50, 250, 200, 100); var roof = stage.path() .moveTo(50, 250) .lineTo(150, 180) .lineTo(250, 250) .close(); // 绘制一个人 var head = stage.circle(330, 280, 10); var neck = stage.path().moveTo(330, 290).lineTo(330, 300); var kilt = stage.triangleUp(330, 320, 20); var rightLeg = stage.path().moveTo(320, 330).lineTo(320, 340); var leftLeg = stage.path().moveTo(340, 330).lineTo(340, 340);
View the results on CodePen.
As you can see, we are now using variables – all methods of drawing content on the stage return a reference to the created object and this link can be used to change or delete the object.
Also note how chain calls (e.g. stage.path().moveTo(320, 330).lineTo(320, 340);
) are everywhere in GraphicsJS, which helps shorten the code. Chained calls should be used with caution, but if applied properly, it does make the code more compact and easier to read.
Now, let's hand this coloring page to a child and let them paint. Because even children can master the following techniques:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>GraphicsJS Basic Example</title> </head> <body> <div id="stage-container" style="width: 400px; height: 375px;"></div> <🎜> <🎜> </body> </html>
This is how our example looks now.
Now, we have a picture of a Highlander standing next to a kilt, standing near his brick castle with straw on the roof. We can even risk saying that this is indeed a work of art that we want to obtain copyright. Let's do this using pattern fills based on custom text:
As you can see, this is easy to do: you create an instance of a text object, then form a pattern on the stage and put the text into the pattern.// 创建舞台 var stage = acgraph.create('stage-container'); // 绘制矩形 var stage.rect(25, 50, 350, 300);
View Color copyrighted houses/graphicsjs on CodePen.
Create a puzzle art game in less than 50 lines of code
The game name is
"Sweeping the Streets in the Wind", and the player plays the role of a scavenger and sweeps the Streets on a windy afternoon in autumn. The game uses some code from the program-generated leaf example in the GraphicsJS gallery. You can view finished games on CodePen (or the end of the article).
Layers, zIndex and virtual DOM
For this game, we will use the layer - the object in GraphicsJS used to group elements. If you want to apply similar changes to elements (such as transformations), you must group elements. You can change the layer in pause mode (more on this later), which can improve performance and user experience.
// 创建舞台 var stage = acgraph.create('stage-container'); // 绘制框架 var frame = stage.rect(25, 50, 350, 300); // 绘制房子 var walls = stage.rect(50, 250, 200, 100); var roof = stage.path() .moveTo(50, 250) .lineTo(150, 180) .lineTo(250, 250) .close(); // 绘制一个人 var head = stage.circle(330, 280, 10); var neck = stage.path().moveTo(330, 290).lineTo(330, 300); var kilt = stage.triangleUp(330, 320, 20); var rightLeg = stage.path().moveTo(320, 330).lineTo(320, 340); var leftLeg = stage.path().moveTo(340, 330).lineTo(340, 340);
In this demo, we use the layer function to help us group the leaves together and avoid them covering the label (it tells us how many leaves are swept). To do this, we create a tag and call the
method, which creates the stage binding layer. We set the property of this layer to the stage.layer
property below the label. zIndex
zIndex
// 给图片着色 // 精美的框架 frame.stroke(["red", "green", "blue"], 2, "2 2 2"); // 砖墙 walls.fill(acgraph.hatchFill('horizontalbrick')); // 草屋顶 roof.fill("#e4d96f"); // 格子呢裙 kilt.fill(acgraph.hatchFill('plaid'));
Convert
You will see that each path is created the same way, but then the conversion will be performed. This will produce a very beautiful random leaf pattern.
// 169 是版权符号的字符代码 var text = acgraph.text().text(String.fromCharCode(169)).opacity(0.2); var pattern_font = stage.pattern(text.getBounds()); pattern_font.addChild(text); // 用图案填充整个图像 frame.fill(pattern_font);
Processing Events
In this game example, we are using an event listener attached to the leaf object so that when the user hovers over them, they disappear one by one. To do this, add the following code to the bottom of the drawLeaves
function, before the return
statement:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>GraphicsJS Basic Example</title> </head> <body> <div id="stage-container" style="width: 400px; height: 375px;"></div> <🎜> <🎜> </body> </html>
Here we can also see that we are using layers to calculate leaves.
// 创建舞台 var stage = acgraph.create('stage-container'); // 绘制矩形 var stage.rect(25, 50, 350, 300);
Please note that we don't actually store the number of leaves here. Since we add leaves to a specific layer and remove leaves from them, this allows us to track how many child elements we have (and therefore how many leaves are left).
GraphicsJS provides a virtual DOM that is an abstract, lightweight and separate from browser-specific SVG/VML implementations. It is very useful for doing many great things like tracking all objects and layers, applying transformations to groups, and optimizing rendering with help allows us to track and control the rendering process.
The virtual DOM and event handlers allow GraphicsJS users to control rendering. Performance articles can help you understand the relationship between these contents.
When generating leaves in the game, we need to pause the rendering when adding new leaves, and only resume the rendering after all changes are completed:
// 创建舞台 var stage = acgraph.create('stage-container'); // 绘制框架 var frame = stage.rect(25, 50, 350, 300); // 绘制房子 var walls = stage.rect(50, 250, 200, 100); var roof = stage.path() .moveTo(50, 250) .lineTo(150, 180) .lineTo(250, 250) .close(); // 绘制一个人 var head = stage.circle(330, 280, 10); var neck = stage.path().moveTo(330, 290).lineTo(330, 300); var kilt = stage.triangleUp(330, 320, 20); var rightLeg = stage.path().moveTo(320, 330).lineTo(320, 340); var leftLeg = stage.path().moveTo(340, 330).lineTo(340, 340);
This method of dealing with new elements makes new leaves appear almost immediately.
Finally, start everything by calling shakeTree()
.
// 给图片着色 // 精美的框架 frame.stroke(["red", "green", "blue"], 2, "2 2 2"); // 砖墙 walls.fill(acgraph.hatchFill('horizontalbrick')); // 草屋顶 roof.fill("#e4d96f"); // 格子呢裙 kilt.fill(acgraph.hatchFill('plaid'));
View Street Cleaner/graphicsjs on CodePen.
The transition to HTML5 has changed the network. When it comes to modern web applications and even simple websites, we often encounter tasks that require image processing. While it is impossible to find a solution that works well in every case, you should consider the GraphicsJS library. It is open source, robust, with excellent browser support and many features that make it fun, convenient and of course useful.
I would love to hear your feedback on GrphicsJS in the comments below. Are you already using it? Would you consider using it for a new project? I'd love to know why, or why not use it. I'm also writing a list of major JavaScript drawing libraries and articles that will compare and compare all of them. Feel free to point out the features you wish to see there.
GraphicsJS stands out for its powerful and lightweight nature. It is a powerful library that allows developers to draw and animate any graphics with high precision and high performance. Unlike other libraries, GraphicsJS provides a comprehensive set of features including layers, gradients, patterns, and more without affecting speed or efficiency. It also supports all modern browsers, making it a versatile option for developers.
To get started with GraphicsJS, you need to include the GraphicsJS library in your HTML file. You can download the library from the official website or use CDN. Once the library is included, you can start creating the graphics by calling the appropriate functions and methods provided by the library.
Yes, GraphicsJS is designed to handle complex animations easily. It provides a rich set of animation features including easing function, delay and duration settings. You can animate any attribute of a graph, such as its position, size, color, and more. This makes GraphicsJS a powerful tool for creating interactive and dynamic graphics.
GraphicsJS is designed to be compatible with all modern browsers, including Chrome, Firefox, Safari, and Internet Explorer. It uses SVG and VML for rendering, all of which support them. This ensures that your graphics look consistent and perform well on different platforms and devices.
Creating gradients with GraphicsJS is simple. You can use the gradient method to define linear or radial gradients, specify colors and positions, and then apply gradients to any shape. This allows you to create colorful graphics easily.
Yes, GraphicsJS provides a set of event handling capabilities that allow you to create interactive graphics. You can attach an event listener to any graph, allowing you to respond to user actions such as clicks, mouse movements, and more. This makes GraphicsJS an excellent choice for creating interactive web applications.
Yes, GraphicsJS supports layers, allowing you to organize graphics into separate groups. Each layer can be operated independently, making it easier to manage complex graphics. You can also control the visibility and z-order of each layer, allowing fine-grained control of the graphics.
GraphicsJS provides several features that can help you optimize your graphics. For example, you can use the crop method to hide parts of the graphics outside of a specified area, thereby reducing the amount of rendering required. You can also use the cache method to store rendered output of the graphics, thereby improving performance when you repaint the graphics frequently.
While GraphicsJS is not designed specifically for creating charts and graphics, its powerful drawing and animation capabilities allow it to create any type of graphics, including charts and graphics. You can use the library's methods to draw lines, curves, rectangles, circles, and more to create various chart types.
Yes, GraphicsJS is a free open source library. You can use it for free in your project. The library is also actively maintained to ensure it is in sync with the latest web standards and technologies.
The above is the detailed content of Introducing GraphicsJS, a Powerful Lightweight Graphics Library. For more information, please follow other related articles on the PHP Chinese website!