Front End Prerequisites--Canvas

Life is meaningless if you don't write code to pretend. It's all 2020. If you're doing front-end development and you don't even use canvas, what do you want to do? Following the author, let's see what canvas is, what it can be used for, and which products are made by canvas.

Introduction to Canvas

1.canvas is a new tag for html5, which is a new feature of h5
2. The canvas tag is a container of graphics, simply a canvas on which you can draw rectangles, circles, triangles, polylines, etc. or logo s
3. It is drawn through javascript, that is, scripted graphics

What can canvas be used for?
1. Make web games (but games that don't write well may be very card-intensive)
2. Data visualization (so you may not understand, but I tell you echarts are based on canvas)
3. The dynamic effect of banner is ideal for canvas production
4.canvas can also be used to embed some web pages

Basic usage of canvas

Sample code:

<body onload="draw()">
    <canvas id="canvas" width="300" height="300"></canvas>
</body>
</html>
<script>
    function draw() {
        // Get Canvas
        var canvas = document.getElementById('canvas');
        if (canvas.getContext) { // Used to verify whether the browser supports canvas, which is a new feature of h5 and not supported by older versions of ie
            var ctx = canvas.getContext("2d"); // Optional 2d and 3d
            ctx.fillStyle = "rgba(200, 0, 0, 1)"; // Fill color
            ctx.fillRect (10, 10, 55, 50); // The first two represent x,y coordinates (relative to canvas, not relative to window), where to start drawing, and the second two represent width and length.

            ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
            ctx.fillRect (30, 30, 55, 50);

            // Draw a rectangle, clear a specific rectangle, draw a border
            ctx.fillRect(100, 100, 100, 100);
            ctx.clearRect(112.5, 112.5, 75, 75); // Clear Rectangle
            ctx.strokeRect(125, 125, 50, 50); // Rectangular Border
        }
    }
</script>

The results are as follows:

Advanced usage of canvas

Draw triangle example code:

	function draw() {
        // Get Canvas
        var canvas = document.getElementById('canvas');
        // Path Drawing Fill Triangle
        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");
            ctx.beginPath(); // Create a new path and draw the specified path
            ctx.moveTo(75, 50);  // Where does the path start
            ctx.lineTo(100, 75); // To which point
            ctx.lineTo(100, 25);  
            ctx.fill();  // Fill the content area to produce a solid graph
			// Draw Edge Triangle
			ctx.beginPath();
            ctx.moveTo(150, 150);
            ctx.lineTo(150, 60);
            ctx.lineTo(60, 150);
            ctx.closePath(); // Path closure method
            ctx.stroke();
        }
    }

The results are as follows:


Sample code for drawing a smiley face:

	function draw() {
        // Get Canvas
        var canvas = document.getElementById('canvas');
        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");
            ctx.beginPath();
            ctx.arc(75, 75, 50, 0, Math.PI * 2, true); // The first two centers, the radius behind them, 0 represents how much to start drawing, Math.PI*2 for full arc length, true for counterclockwise
            ctx.moveTo(110, 75); // Where to move and where to start drawing
            ctx.arc(75, 75, 35, 0,Math.PI, false); // Draw a semicircle clockwise (mouth)
            ctx.moveTo(65, 65);
            ctx.arc(60, 65, 5, 0, Math.PI * 2, true);  // Small circle of left eye
            ctx.moveTo(95, 65);
            ctx.arc(90, 65, 5, 0, Math.PI * 2, true); // Right eye small circle
            ctx.stroke();
        }
    }

The results are as follows:

Quadratic Bezier Curve Paint Message Box and Cubic Bezier Curve Paint Love

	function draw() {
        // Get Canvas
        var canvas = document.getElementById('canvas');
        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");
            ctx.beginPath();
            ctx.moveTo(75, 25);
            ctx.quadraticCurveTo(25, 25, 25, 62.5);
            ctx.quadraticCurveTo(25, 100, 50, 100);
            ctx.quadraticCurveTo(50, 120, 30, 125);
            ctx.quadraticCurveTo(60, 120, 65, 100);
            ctx.quadraticCurveTo(125, 100, 125, 62.5);
            ctx.quadraticCurveTo(125, 25, 75, 25);
            ctx.stroke();
        }
    }

The results are as follows:

Paint love code:

	function draw() {
        // Get Canvas
        var canvas = document.getElementById('canvas');
        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");
            ctx.beginPath();
            ctx.moveTo(75, 40);
            ctx.bezierCurveTo(75, 37, 70, 25, 50, 25);
            ctx.bezierCurveTo(20, 25, 20, 62.5, 20, 62.5);
            ctx.bezierCurveTo(20, 80, 40, 102, 75, 120);
            ctx.bezierCurveTo(110, 102, 130, 80, 130, 62.5);
            ctx.bezierCurveTo(130, 62.5, 130, 25, 100, 25);
            ctx.bezierCurveTo(85, 25, 75, 37, 75, 40);
            ctx.fill();
        }
    }

The results are as follows:

Dynamic Style Color Code:

	function draw() {
        // Get Canvas
        var ctx = document.getElementById('canvas').getContext("2d");
        for (var i = 0; i < 6; i++) {
            for (var j = 0; j < 6; j++) {
                ctx.fillStyle = 'rgb(' + Math.floor(255-42.5*i) + ',' + 
                   Math.floor(255-42.5*j) + ', 0)';
                   ctx.fillRect(j * 25, i * 25, 25, 25);
            }
        }
        // for (var i=0;i<6;i++){
        //     for (var j=0;j<6;j++){
        //         ctx.strokeStyle = 'rgb(0,' + Math.floor(255-42.5*i) + ',' + 
        //                         Math.floor(255-42.5*j) + ')';
        //         ctx.beginPath();
        //         ctx.arc(12.5+j*25,12.5+i*25,10,0,Math.PI*2,true);
        //         ctx.stroke();
        //     }
        // }
        // Paint Background
        // ctx.fillStyle = '#FD0';
        // ctx.fillRect(0,0,75,75);
        // ctx.fillStyle = '#6C0';
        // ctx.fillRect(75,0,75,75);
        // ctx.fillStyle = '#09F';
        // ctx.fillRect(0,75,75,75);
        // ctx.fillStyle = '#F30';
        // ctx.fillRect(75,75,75,75);
        // Ctx. FillStyle ='#FFF'; // Here is the fill color of the circle! [Insert picture description here] ( https://img-blog.csdnimg.cn/20200923164433952.png#pic_center)


        // Set Transparency Value
        // ctx.globalAlpha = 0.2;

        // Draw a translucent circle
        // for (var i=0;i<7;i++){
            // ctx.beginPath();
            // ctx.arc(75,75,10+10*i,0,Math.PI*2,true);
            // ctx.fill();
        // }
    }

The results are as follows:



Make your own personal text logo code:

	function draw() {
        // Get Canvas
        var ctx = document.getElementById('canvas').getContext("2d");
        ctx.shadowOffsetX = 4;
        ctx.shadowOffsetY = 4;
        ctx.shadowBlur = 4;
        ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
        
        ctx.font = "30px Times New Roman";
        ctx.fillStyle = "black";
        ctx.fillText("Siberian Wolf", 5, 30);

		// ctx.font = "48px serif";
        // ctx.textBaseline = "hanging";
        // Ctx. StrokeText (Siberian wolf, 10, 100);
		
		// Line Graph Initial Form
        // ctx.beginPath();
        // ctx.moveTo(20, 200);
        // ctx.lineTo(60, 160);
        // ctx.lineTo(100, 160);
        // ctx.lineTo(160, 100);
        // ctx.stroke();

    }

The effect diagram is as follows (example):


Advanced Animation

The solar system animation code is as follows (example):

	var sun = new Image();
    var moon = new Image();
    var earth = new Image();
    function init(){
    sun.src = 'https://mdn.mozillademos.org/files/1456/Canvas_sun.png';
    moon.src = 'https://mdn.mozillademos.org/files/1443/Canvas_moon.png';
    earth.src = 'https://mdn.mozillademos.org/files/1429/Canvas_earth.png';
    window.requestAnimationFrame(draw);
    }

    function draw() {
    var ctx = document.getElementById('canvas').getContext('2d');

    ctx.globalCompositeOperation = 'destination-over';
    ctx.clearRect(0,0,300,300); // clear canvas

    ctx.fillStyle = 'rgba(0,0,0,0.4)';
    ctx.strokeStyle = 'rgba(0,153,255,0.4)';
    ctx.save();
    ctx.translate(150,150);

    // Earth
    var time = new Date();
    ctx.rotate( ((2*Math.PI)/60)*time.getSeconds() + ((2*Math.PI)/60000)*time.getMilliseconds() );
    ctx.translate(105,0);
    ctx.fillRect(0,-12,50,24); // Shadow
    ctx.drawImage(earth,-12,-12);

    // Moon
    ctx.save();
    ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + ((2*Math.PI)/6000)*time.getMilliseconds() );
    ctx.translate(0,28.5);
    ctx.drawImage(moon,-3.5,-3.5);
    ctx.restore();

    ctx.restore();
    
    ctx.beginPath();
    ctx.arc(150,150,105,0,Math.PI*2,false); // Earth orbit
    ctx.stroke();
    
    ctx.drawImage(sun,0,0,300,300);

    window.requestAnimationFrame(draw);
    }

    init();

The results are as follows:

The cool mouse follows the animation code as follows:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <script>
            var cn;
            //= document.getElementById('cw');
            var c;
            var u = 10;
            const m = {
                x: innerWidth / 2,
                y: innerHeight / 2
            };
            window.onmousemove = function(e) {
                m.x = e.clientX;
                m.y = e.clientY;

            }
            function gc() {
                var s = "0123456789ABCDEF";
                var c = "#";
                for (var i = 0; i < 6; i++) {
                    c += s[Math.ceil(Math.random() * 15)]
                }
                return c
            }
            var a = [];
            window.onload = function myfunction() {
                cn = document.getElementById('cw');
                c = cn.getContext('2d');

                for (var i = 0; i < 10; i++) {
                    var r = 30;
                    var x = Math.random() * (innerWidth - 2 * r) + r;
                    var y = Math.random() * (innerHeight - 2 * r) + r;
                    var t = new ob(innerWidth / 2,innerHeight / 2,5,"red",Math.random() * 200 + 20,2);
                    a.push(t);
                }
                //cn.style.backgroundColor = "#700bc8";

                c.lineWidth = "2";
                c.globalAlpha = 0.5;
                resize();
                anim()
            }
            window.onresize = function() {

                resize();

            }
            function resize() {
                cn.height = innerHeight;
                cn.width = innerWidth;
                for (var i = 0; i < 101; i++) {
                    var r = 30;
                    var x = Math.random() * (innerWidth - 2 * r) + r;
                    var y = Math.random() * (innerHeight - 2 * r) + r;
                    a[i] = new ob(innerWidth / 2,innerHeight / 2,4,gc(),Math.random() * 200 + 20,0.02);

                }
                //  a[0] = new ob(innerWidth / 2, innerHeight / 2, 40, "red", 0.05, 0.05);
                //a[0].dr();
            }
            function ob(x, y, r, cc, o, s) {
                this.x = x;
                this.y = y;
                this.r = r;
                this.cc = cc;
                this.theta = Math.random() * Math.PI * 2;
                this.s = s;
                this.o = o;
                this.t = Math.random() * 150;

                this.o = o;
                this.dr = function() {
                    const ls = {
                        x: this.x,
                        y: this.y
                    };
                    this.theta += this.s;
                    this.x = m.x + Math.cos(this.theta) * this.t;
                    this.y = m.y + Math.sin(this.theta) * this.t;
                    c.beginPath();
                    c.lineWidth = this.r;
                    c.strokeStyle = this.cc;
                    c.moveTo(ls.x, ls.y);
                    c.lineTo(this.x, this.y);
                    c.stroke();
                    c.closePath();

                }
            }
            function anim() {
                requestAnimationFrame(anim);
                c.fillStyle = "rgba(0,0,0,0.05)";
                c.fillRect(0, 0, cn.width, cn.height);
                a.forEach(function(e, i) {
                    e.dr();
                });

            }
        </script>
        <style>
            #cw {
                position: fixed;
                z-index: -1;
            }

            body {
                margin: 0;
                padding: 0;
                background-color: rgba(0,0,0,0.05);
            }
        </style>
    </head>
    <body>
        <canvas id="cw"></canvas>
        qwerewr    

    </body>
</html>

The results are as follows:

summary

Canvas is a very powerful drawing board. After reading the author's sample code, I hope you can get some results. Canvas can do a lot of mouse follow and dynamic particle animation. Have you learned canvas and you can't be overwhelmed by it? Your favorite buddies remember to collect it and welcome you to communicate and learn together.

Keywords: Javascript Front-end css3 html css

Added by f8ball on Tue, 01 Mar 2022 20:32:29 +0200