How to draw complex graphics with JavaScript

PHPz
Release: 2023-04-18 17:05:33
Original
832 people have browsed it

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 id="myCanvas">
  Your browser does not support this feature.
</canvas>
Copy after login

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');
Copy after login

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);
Copy after login

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();
Copy after login

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);
Copy after login

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);
Copy after login

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);
Copy after login

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';
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template