Home Web Front-end H5 Tutorial Canvas realizes the drawing of rotating windmill

Canvas realizes the drawing of rotating windmill

Mar 27, 2018 am 09:23 AM
canvas draw

This time I will bring you the drawing of rotating windmills with Canvas. What are the precautions for drawing rotating windmills with Canvas? Here are the actual cases, let’s take a look.

Before teaching, I think if you are smart, you have mastered the basic basic operation methods of Canvas. If you don’t know much about Canvas, then I suggest you go to http://www.w3school.com.cn /tags/html_ref_canvas.asp Get familiar with it first;

okey! The picture below is the simple effect after we complete it. Action is not as good as action, so let’s do a simple drawing!

1. Define the canvas

First of all, we insert the tag into the html file to define the size of the canvas. The size of the canvas defined here is 800*600 pixels. At the same time, set the background color of the canvas in the internal style sheet (convenient for viewing when drawing);

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        body{
            padding: 0;
            margin: 0;
        }
        #canvas {
            background:#5151a2;
        }
    </style>
</head>
<body>
    <canvas id="canvas" width="800" height="600"></canvas>
</body>
</html> 
Copy after login
The next core is to draw the windmill in the native JS environment; through JS

DOM operation method Obtain the canvas element object and obtain the 2D drawing context through getContex("2d"). This method is like telling the browser "We want to draw 2D graphics on this canvas";

<script type="text/javascript">
    //获取画布的2d上下文
    var ctx = document.getElementById("canvas").getContext("2d");
Copy after login

2. Draw the base of the windmill

The geometric figure of the base of the windmill looks like a long and slender trapezoid. We can draw a trapezoid and then fill it with color. Here, in order to achieve a relatively small Good effect, using the color gradient filling method; okey! Just look at the code~~!

    //定义一个函数 ,封装风车的底部基座
    function buttom(){
        ctx.beginPath();                                        //开始一条新的绘制路径
        var liner = ctx.createLinearGradient(390,600,410,600);    //设置变量(颜色渐变的方向-起点-终点)
        liner.addColorStop(0,"#ccc");                            //设置起点颜色
        liner.addColorStop(0.5,"#fff");                            //设置中点颜色
        liner.addColorStop(1,"#ccc");                            //设置终点颜色
        ctx.fillStyle = liner;                                    //梯形的填充方式设置为 变量(渐变颜色)    
        ctx.moveTo(395,300);                                    //提起我们的画笔,起点设置为(395,300)
        ctx.lineTo(405,300);                                    //连接起点画线
        ctx.lineTo(410,600);
        ctx.lineTo(390,600);                                    
        ctx.closePath();                                        //闭合路径
        ctx.fill();                                                //填充梯形
        
    }
  buttom();                              //要调用函数,才能在浏览器显示
Copy after login
Let’s take a look at the effect on the page. Is it very simple?

(I feel like I talk a bit too much~!~!)

3. Draw leaves

The next part will be the most critical part of this animation. First, let’s analyze the structure of the leaves. The angle between the three leaves is 120°, and the shape of each leaf is the same; they have a center, and you may also have one in your mind. I have a question, should I draw the center of the circle first or the leaves first? How should I draw the shape of the leaves? Can the leaves be copied and pasted? The answer is of course yes, Let's do it!

Idea analysis:

1). Since the shapes of the three leaves are exactly the same, we only need to draw one leaf, and just copy the second and third leaves directly. We are smart Shouldn't we encapsulate a function for this leaf drawing method? Just call it the bind( ) function! ! Just call it every time! Why! You guys are so smart

2). The three leaves have a center of a circle. In order to facilitate the coordinate values ​​when drawing the leaves, we move the center of the circle from the upper left corner of the drawing to the top of the trapezoid, so that it will be much more convenient for us to draw the leaves. ! The translate() method is used here to move the coordinate system!

3) The most difficult point is to understand how the animation is implemented here, because the animation principle will affect the document structure of our leaf drawing:

First we create a new drawing environment, we Call it environment 1. We draw the first leaf on environment 1; then rotate 120° to create the first drawing environment 2 under the premise of the first drawing environment, and then call the function bind( ) for drawing leaves. , draw two leaves; the third leaf is drawn in the same way, rotate 120° on the basis of environment 2, create a new environment 3, and call the leaf drawing function bind( ) to draw the third leaf;

If you want To implement animation, we only need to rotate the drawing environment 1 of the first leaf. The second leaf and the third leaf are drawn with reference to environment 1. Do they also move? ? Barrage: 666666

4), and finally some basic appearance style debugging! For example, color gradient, transparency, etc.!

Drawing leaves

When I drew this leaf shape, I adjusted it slowly. My aesthetics are quite low, forgive me. I can only draw such leaves. Of course, students with rich imagination can draw them according to their own preferences, but the general idea is the same;

Here I declare a variable var num = 0;, as the environment 1 rotation A parameter of degree change: Then let’s look at the code directly! ! !

var num =0;
function yezi(){
        ctx.save();  //保存默认情况下的canvas变换状态
        ctx.beginPath();
        ctx.translate(400,300);
        // ctx.globalAlpha = 0.9;
        // 设置第一次状态下 坐标系旋转度数
        ctx.rotate((Math.PI/180)*num);
        var liner1 = ctx.createLinearGradient(30,-12,30,12);      //这里设置颜色渐变填充的样式
            liner1.addColorStop(0,"#ccc");
            liner1.addColorStop(0.5,"#fff");
            liner1.addColorStop(1,"#ccc");
            ctx.fillStyle = liner1;
        ctx.save();                 //保存第一次状态  平移坐标系变换
            ctx.beginPath();
            bind();                //调用函数
            //绘制第二片叶子
            ctx.beginPath();
            ctx.rotate((Math.PI/180)*120);   //坐标系旋转120°
            ctx.save();                        //保存旋转坐标系状态,为第三片叶子做铺垫
                bind();            //调用函数
                //绘制第三片叶子
                ctx.beginPath();
                ctx.rotate((Math.PI/180)*120);   //坐标系旋转120°
                ctx.save();    
                    bind();     //调用函数
                ctx.restore();    //回复第3次状态前(旋转坐标系)
            ctx.restore();        //回复第2次状态前(旋转坐标系)
            //绘制叶子中心圆圈
            ctx.beginPath();
            var arcgradient = ctx.createRadialGradient(0,0,0,0,0,16);
            arcgradient.addColorStop(0,"#ccc");
            arcgradient.addColorStop(0.1,"#fff");
            arcgradient.addColorStop(1,"#ccc");
            ctx.arc(0,0,10,0,Math.PI*2);
            ctx.fillStyle  = arcgradient;
            ctx.fill();
        ctx.restore();             //回复第1次状态前(平移坐标系)
        num+=5;   //第一状下  环境1   态坐标系旋转度数增加********************************这个num使得环境1的旋转角度在不停的变化,**********************************************
        ctx.restore();
    }
    //绘制每片叶子都重复的代码,这里做一个函数包装
    function bind(){
        ctx.moveTo(0,0);                    
        ctx.quadraticCurveTo(10,-12,30,-12);    //比赛尔曲线
        ctx.lineTo(190,-3);
        ctx.quadraticCurveTo(200,0,190,3);    
        ctx.lineTo(30,12);
        ctx.moveTo(0,0);
        ctx.quadraticCurveTo(10,12,30,12);
        ctx.fill();
    }
Copy after login

4、设置动画

动画这部分就比较简单了,设置定时器,清除画布,调用函数;大功告成,打完收工!!!

setInterval(function(){
        ctx.clearRect(0,0,800,600);    //每次执行代码前,都要将画布清空,不然画出的图形会滞留在画布上;
        buttom();               //调用函数 
        yezi();
    },50);
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

H5如何做出碎片式的图片切换

怎样用H5计算手机摇动次数

H5调用相机拍照并压缩图片

The above is the detailed content of Canvas realizes the drawing of rotating windmill. For more information, please follow other related articles on the PHP Chinese website!

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

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can the floor plan be drawn directly in architectural ppt? Can the floor plan be drawn directly in architectural ppt? Mar 20, 2024 am 08:43 AM

ppt is widely used in many fields and work, especially in education, architecture, etc. When it comes to architectural ppt, we must first think of the presentation of some architectural drawings. If we do not use professional drawing software, can we directly draw a simple architectural plan? In fact, we can complete the operation here. Below, we will draw a relatively simple floor plan to give you an idea. I hope you can complete better floor plan drawings based on this idea. 1. First, we double-click to open the ppt software on the desktop and click to create a new presentation blank document. 2. We find Insert→Shape→Rectangle in the menu bar. 3. After drawing the rectangle, double-click the graphic and modify the fill color type. Here we can modify

Learn to draw dendrograms and radar charts in Python in five minutes Learn to draw dendrograms and radar charts in Python in five minutes Sep 27, 2023 pm 12:48 PM

Learn to draw dendrograms and radar charts with Python in five minutes. In data visualization, dendrograms and radar charts are two commonly used chart forms. Treemaps are used to show hierarchical structures, while radar charts are used to compare data across multiple dimensions. This article will introduce how to draw these two charts using Python and provide specific code examples. 1. Drawing dendrograms There are multiple libraries in Python that can be used to draw dendrograms, such as matplotlib and graphviz. The following uses the matplotlib library as an example to demonstrate

How to draw a 3D geographic chart with Python How to draw a 3D geographic chart with Python Sep 28, 2023 am 10:19 AM

Overview of how to draw 3D geographic charts with Python: Drawing 3D geographic charts can help us understand geographic data and spatial distribution more intuitively. Python, as a powerful and easy-to-use programming language, provides many libraries and tools for drawing various types of geographical charts. In this article, we will learn how to draw 3D geographic charts using the Python programming language and some popular libraries such as Matplotlib and Basemap. Environment preparation: Before starting, we need to make sure

What versions of html2canvas are there? What versions of html2canvas are there? Aug 22, 2023 pm 05:58 PM

The versions of html2canvas include html2canvas v0.x, html2canvas v1.x, etc. Detailed introduction: 1. html2canvas v0.x, which is an early version of html2canvas. The latest stable version is v0.5.0-alpha1. It is a mature version that has been widely used and verified in many projects; 2. html2canvas v1.x, this is a new version of html2canvas.

Learn the canvas framework and explain the commonly used canvas framework in detail Learn the canvas framework and explain the commonly used canvas framework in detail Jan 17, 2024 am 11:03 AM

Explore the Canvas framework: To understand what are the commonly used Canvas frameworks, specific code examples are required. Introduction: Canvas is a drawing API provided in HTML5, through which we can achieve rich graphics and animation effects. In order to improve the efficiency and convenience of drawing, many developers have developed different Canvas frameworks. This article will introduce some commonly used Canvas frameworks and provide specific code examples to help readers gain a deeper understanding of how to use these frameworks. 1. EaselJS framework Ea

uniapp implements how to use canvas to draw charts and animation effects uniapp implements how to use canvas to draw charts and animation effects Oct 18, 2023 am 10:42 AM

How to use canvas to draw charts and animation effects in uniapp requires specific code examples 1. Introduction With the popularity of mobile devices, more and more applications need to display various charts and animation effects on the mobile terminal. As a cross-platform development framework based on Vue.js, uniapp provides the ability to use canvas to draw charts and animation effects. This article will introduce how uniapp uses canvas to achieve chart and animation effects, and give specific code examples. 2. canvas

Learn to draw line charts, bar charts and pie charts with Python in three minutes Learn to draw line charts, bar charts and pie charts with Python in three minutes Sep 27, 2023 am 09:29 AM

Learn to draw line charts, bar charts, and pie charts with Python in three minutes. Python is a very popular programming language that is widely used in data analysis and visualization. In this article, we will learn how to draw three common types of charts using Python: line charts, bar charts, and pie charts. I'll provide you with specific code examples to help you get started quickly. Line Chart A line chart is a type of chart that shows trend changes by connecting data points. In Python, we can use the matplotlib library to plot

How to draw animated charts with Python How to draw animated charts with Python Sep 27, 2023 am 09:53 AM

How to Draw Animated Charts with Python As a powerful programming language, Python can be used for various data visualization and chart drawing. Among them, drawing animated charts can make the data more vivid and interesting. This article will introduce how to use Python to draw animated charts and provide specific code examples. First, we need to install the matplotlib library, which is one of the most commonly used charting libraries in Python. Run the following command in the terminal to install matplotlib: pipinsta

See all articles