To do a good job, he must sharpen his tools. To build your own visualization engine, you must first be familiar with the Cavas API. You can refer to Canvas MDN for a detailed Canvas tutorial. The Cavas API is briefly explained below.

Basic usage

<canvas> is a new element in HTML 5 that creates a fixed-size canvas in the browser. Get a reference to the HTML <canvas> element through the document.getelementByid () method. HTMLCanvasElement. GetContext () method to get the canvas context context, we may call it the brush. With the brush, we can draw shapes on the canvas. Here is a simple example of an official drawing green rectangle:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'green'; // Set the pen color to green ctx.fillrect (10, 10, 150, 100); // Draw a rectangle with width 150 and height 100 at coordinates (10, 10)Copy the code

Drawing API

Cavas provides us with a number of drawing apis, and we’ll briefly cover the ones we’ll use in this series. For more details, see Canvas MDN.

Draw function

  • ClearRect (x, y, width, height); FillRect (x, y, width, height); StrokeRect (x, y, width, height);
  • BeginPath (); Move the pen to the specified coordinate moveTo(x, y). LineTo (x, y) from the current position to the specified coordinates; Draw the radius of the arc(x, y, radius, startAngle, endAngle, anticlockwise) at the specified coordinates; QuadraticCurveTo (cp1x, cp1y, x, y); Draw three Bezier curves bezierCurveTo(cp1x, CP1y, CP2x, cp2Y, x, y); Close the path closePath(); Draw graph contour stroke(); Fill the graph path stroke();
  • FillText (text, x, y [, maxWidth]); StrokeText (text, x, y [, maxWidth]);
  • DrawImage (image, sx, sy, [sWidth, sHeight, dx, dy, dWidth, dHeight]);

style

  • Color: fillStyle(fill color)/strokeStyle(outline color);
  • Transparency: globalAlpha;
  • Linear: lineWidth /lineCap /lineJoin /miterLimit;
  • CreateRadialGradient (x1, y1, R1, x2, [y2, R2])/addColorStop(position, color)
  • Shadow: shadowOffsetX(X axis shadow)/shadowOffsetY(Y axis shadow)/shadowBlur(blur)/shadowColor

other

  • Save () saves the brush state
  • Restore () restores a snapshot of the state of the brush when it was saved
  • Translate (x, y) The canvas position is offset
  • Rotate (Angle) Rotate the canvas
  • Scale (x, y) Canvas scale

In the following example, we will make a simple application of the above API

<canvas id="canvas" width="500" height="500"></canvas>
<button onclick="draw('rect')"<button onclick= <button onclick="draw('rect_str')"<button onclick= <button onclick="draw('angle3')"> </button> <button onclick="draw('arc')"<button onclick= <button onclick="draw('bezier')"< p style = "max-width: 100%; clear: bothtype="text/javascript">
    let canvas = document.getElementById('canvas');
    let ctx = canvas.getContext('2d');
    function draw(type) {
    	let posX = Math.round(Math.random() * 500);
    	let posY = Math.round(Math.random() * 500);
    	if (type= = ='rect') {
    		ctx.fillRect(posX, posY, 100, 150);
    	} else if(type= = ='rect_str') {
    		ctx.strokeRect(posX, posY, 100, 100);
    	} else if(type= = ='angle3') {
    		ctx.beginPath();
    		ctx.moveTo(posX, posY);
    		ctx.lineTo(posX + 50, posY - 50);
    		ctx.lineTo(posX, posY - 100);
    		ctx.closePath();
    		ctx.fill();
    	} else if(type= = ='arc') {
    		ctx.beginPath();
    		ctx.arc(posX, posY, 50, 0, Math.PI * 2, true);
    		ctx.closePath();
    		ctx.stroke();
    	} else if(type= = ='bezier') { ctx.beginPath(); CTX. MoveTo (75, 40); CTX. BezierCurveTo,37,70,25,50,25 (75); CTX. BezierCurveTo (20,25,20,62.5, 20,62.5); CTX. BezierCurveTo,80,40,102,75,120 (20); CTX. BezierCurveTo,80,130,62.5 (110102130); CTX. BezierCurveTo (130,62.5, 130,25,100,25); CTX. BezierCurveTo,25,75,37,75,40 (85); ctx.fill(); }else if(type= = ='text') {
    		ctx.font="20px Georgia";
    		ctx.fillText("Hello World!", posX, posY);
    	}
    }
</script>
Copy the code

Encapsulation Canvas

Canvas class

As can be seen from the previous example, the <canvas> tag must be created every time a graph is drawn, and the brush object context must be saved to draw the graph through the context. In order to better manage the canvas in the future, we have encapsulated the canvas here. This engine manages primitives in an object-oriented manner.

Recognize the difference between the CanvasWidth property and the style Width

Before wrapping the Canvas class, let’s look at the difference between the Canvas Width property and the Canvas style width. The width property is the width of the Canvas Canvas, and the style width is the width in the Canvas document flow. The style width is the actual pixel size of the canvas in the document flow. The width property is the width of the canvas. The virtual width relative to the brush can be understood as the fineness of the brush. Assuming the canvas style width is 300px and the canvas width property is 600px, this means that the brush can draw a width of 0.5px relative to the document page. By default, the Canvas Width property and style property of a Canvas are 1:1.

code

class Canvas {
	constructor(config) {
		if (config.ele === undefined) {
		  throw new Error('Not found config of canvas element'); } // Canvas's container tag this.container = config.ele; / / set the canvas width attributes the ratio of width and style this. Thewire = config. Thewire | | 2. // Create canvas tag this.canvas = document.createElement('canvas'); this.childs = []; this.init(); } /** * resize the Canvas */repaint() {
		this.container.innerHTML = ' ';
		this.canvas = document.createElement('canvas'); this.init(); } /** * initializes Canvas coefficient */initConst styles = getComputedStyle(this.container, null); // Const width = parseInt(styles.width); // High const height = parseInt(styles.height); // Set the canvas style width this.canvas.style.width = '${width}px`; // Set the canvas style to high this.canvas.style.height = '${height}px`; This.canvas. Width = this.ratio * width; This.canvas. Height = this.ratio * height; / / remove click selected style this. Canvas. Style. The outline ='none'; this.canvas.onclick = (e) => { this.canvas.focus(); }; this.container.appendChild(this.canvas); // Set the brush property this.painter = this.canvas.'2d'); }}Copy the code

Based on the above code, we only need to create a Canvas class to obtain the brush tool. The example is as follows:

<style>
.bigger{
	width: 200px;
	height:200px;
}
</style>
<div class="bigger" id="canvas" />
let dv = document.getElementById('canvas');
let canvas = new Canvas({
	ele: dv
});
canvas.painter.fillRect(0, 0, 100, 150);
Copy the code

directory

【 Realization of my own visualization engine 01】 Understanding Canvas 【 realization of my own Visualization framework engine 02】 Abstract image elements 【 Realization of my own visualization engine 03】 Construction of basic metalibrary 【 Realization of my own visualization engine 04】 Image elements animation 【 Realization of my own visualization engine 05】 interaction and events [Realize my own visualization engine 06] broken line chart [realize my own visualization engine 07] Bar chart [Realize my own visualization engine 08] Bar chart [Realize my own visualization engine 09] pie chart [Realize my own visualization engine 10] Scatter chart [Realize my own visualization engine 11] Radar chart [Achieve your own visualization engine 12] K-line [achieve your own visualization engine 13] Dashboard [achieve your own visualization engine 14] map [achieve your own visualization engine 15] diagram