search
HomeWeb Front-endFront-end Q&AHow to draw complex graphics with JavaScript

JavaScript is a very powerful programming language that plays an important role in modern web development. In addition to realizing web page interaction and dynamic effects, JavaScript can also realize various complex graphics through the drawing API. So, this article will share with you how to draw complex graphics with JavaScript.

Canvas and Context

To implement graphics in Javascript, we need to first create a canvas (Canvas) element and then obtain its context (Context). Canvas is an HTML5 tag that allows you to create a rectangular area with drawing capabilities on a web page. The purpose of obtaining the context is to use the drawing API provided by canvas.

Creating a Canvas element is very simple, just add the following code in HTML:

<canvas>
  Your browser does not support this feature.
</canvas>

The id attribute can be used to get the canvas element, and the text nested in the middle of the label is not Alternative text displayed in browsers that support canvas. Next, we can use JavaScript to get the canvas element and context. The code is as follows:

let canvas = document.getElementById('myCanvas');
let ctx = canvas.getContext('2d');

Here, use the getElementById method of the document object to obtain the canvas element with the id myCanvas, and obtain the 2D context through the getContext method. Canvas supports 3 context types: 2D, WebGL and WebGL2. In this article we will use 2D context.

Draw basic shapes

After obtaining the 2D context, we can start drawing. The Canvas API provides a series of methods for describing basic shapes, commonly used ones are: rect, arc, line, etc.

For example, we can draw a rectangle through the following code:

ctx.fillStyle = "#FF0000";
ctx.fillRect(10, 10, 50, 50);

In the above code, the fillStyle property is used to set the fill color, and the fillRect method is used to draw the rectangle. The parameters of the fillRect method are the coordinates of the upper left corner of the rectangle (x, y), and the width and height of the rectangle (width, height).

Next, we can draw a circle through the following code:

ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.fillStyle = "#FFFF00";
ctx.fill();

In the above code, use the beginPath method to start drawing a new path, and the arc method is used to draw a circular path. The parameters are Circle center coordinates (x, y), radius (r), starting angle (startAngle) and ending angle (endAngle). Since we want to draw a complete circle, the starting angle is 0 and the ending angle is 2π. Finally, set the fill color to yellow and use the fill method to fill the path.

Drawing complex shapes

In addition to basic shapes, we can also use the Canvas API to draw various complex shapes. This requires the use of Path2D objects and Bezier curves.

Path2D object is a data structure that saves paths. Complex paths can be described through this object. For example, the following code draws a path composed of 3 line segments:

let path = new Path2D();
path.moveTo(0, 0);
path.lineTo(0, 50);
path.lineTo(50, 50);
ctx.stroke(path);

In the above code, use the moveTo method to set the starting point of the path to (0,0), and use the lineTo method to draw 3 line segments in sequence. , and finally use the stroke method to draw the path.

The Bézier curve is a mathematical function used to describe smooth curves. The Canvas API provides two methods, quadraticCurveTo and bezierCurveTo, to draw quadratic and cubic Bezier curves.

For example, the following code draws a cubic Bezier curve path composed of 3 points:

let path = new Path2D();
path.moveTo(20, 20);
path.bezierCurveTo(20, 100, 200, 100, 200, 20);
ctx.stroke(path);

In the above code, use the moveTo method to set the starting point of the path to (20,20 ), the bezierCurveTo method is followed by three sets of parameters, namely 2 control points and 1 end point. According to the definition of cubic Bezier curve, the starting point and end point are on the curve, and the control points affect the curvature of the curve.

Draw gradients and pictures

In addition to shapes, the Canvas API also supports gradient and picture drawing. First look at how gradients are drawn.

Gradient can be used for fill color or stroke color. The Canvas API supports linear gradients and radial gradients. The following is the code to fill a rectangle using a linear gradient:

let gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
gradient.addColorStop(0, '#FF0000');
gradient.addColorStop(1, '#00FF00');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);

In the above code, the createLinearGradient method is used to create a linear gradient, and the parameters are the starting point coordinates (x0, y0) and the end point coordinates (x1, y1). The addColorStop method is used to set the position and value of the gradient color, where the position parameter is a value between 0 and 1.

Next, let’s take a look at picture drawing.

Canvas API supports using pictures as canvas, which can achieve more complex effects. The following is the code to fill a rectangle with a picture:

let img = new Image();
img.onload = function(){
  let pattern = ctx.createPattern(img, 'repeat');
  ctx.fillStyle = pattern;
  ctx.fillRect(0, 0, canvas.width, canvas.height);
};
img.src = 'image.png';

In the above code, we first create a picture object and set the onload event for it. After the image is loaded, we use the createPattern method to create the pattern, and the parameters are the image object and the drawing method ('repeat' means tile expansion). Finally, use the fillRect method to fill the pattern.

Summary

Through the introduction to the Canvas API, we can know that JavaScript can be used to draw various complex graphics. In addition to basic shapes, various complex paths can be described through Path2D objects and Bezier curves. Through gradients and picture drawing, we can also achieve richer effects. Of course, this is just a brief introduction. The Canvas API is rich in functions and has many more advanced application methods, which require us to continue to learn and practice.

The above is the detailed content of How to draw complex graphics with JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is useEffect? How do you use it to perform side effects?What is useEffect? How do you use it to perform side effects?Mar 19, 2025 pm 03:58 PM

The article discusses useEffect in React, a hook for managing side effects like data fetching and DOM manipulation in functional components. It explains usage, common side effects, and cleanup to prevent issues like memory leaks.

Explain the concept of lazy loading.Explain the concept of lazy loading.Mar 13, 2025 pm 07:47 PM

Lazy loading delays loading of content until needed, improving web performance and user experience by reducing initial load times and server load.

What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code?What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code?Mar 18, 2025 pm 01:44 PM

Higher-order functions in JavaScript enhance code conciseness, reusability, modularity, and performance through abstraction, common patterns, and optimization techniques.

How does currying work in JavaScript, and what are its benefits?How does currying work in JavaScript, and what are its benefits?Mar 18, 2025 pm 01:45 PM

The article discusses currying in JavaScript, a technique transforming multi-argument functions into single-argument function sequences. It explores currying's implementation, benefits like partial application, and practical uses, enhancing code read

How does the React reconciliation algorithm work?How does the React reconciliation algorithm work?Mar 18, 2025 pm 01:58 PM

The article explains React's reconciliation algorithm, which efficiently updates the DOM by comparing Virtual DOM trees. It discusses performance benefits, optimization techniques, and impacts on user experience.Character count: 159

What is useContext? How do you use it to share state between components?What is useContext? How do you use it to share state between components?Mar 19, 2025 pm 03:59 PM

The article explains useContext in React, which simplifies state management by avoiding prop drilling. It discusses benefits like centralized state and performance improvements through reduced re-renders.

How do you prevent default behavior in event handlers?How do you prevent default behavior in event handlers?Mar 19, 2025 pm 04:10 PM

Article discusses preventing default behavior in event handlers using preventDefault() method, its benefits like enhanced user experience, and potential issues like accessibility concerns.

What are the advantages and disadvantages of controlled and uncontrolled components?What are the advantages and disadvantages of controlled and uncontrolled components?Mar 19, 2025 pm 04:16 PM

The article discusses the advantages and disadvantages of controlled and uncontrolled components in React, focusing on aspects like predictability, performance, and use cases. It advises on factors to consider when choosing between them.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment