Create and use the design art of canvas

Source: Internet
Author: User

Do you know <canvas>? If you are not familiar with <canvas>, the best way to learn it is to look at a simple example. The following HTML and JavaScript will generate an orange rectangle in the <canvas> area. Recommendation learningHTML advanced tutorial.

<Canvas id = "example1" width = "400" height = "300"> </canvas>
// Get the canvasvar canvas = document. getElementById ('example1 ');//
Get the "2d" contextvar context = canvas. getContext ('2D ');//
Change fill style to orangecontext. fillStyle = '# ff7700 ';//
Draw an orange rectanglecontext. fillRect (0, 0,400,300 );
You always find the elements in the web document and select "context" to start canvas painting. In this example, the context is 2 d, because we want to use canvas to draw a two-dimensional shape. After selecting a context, the canvas API contains many useful drawing functions, such as fill style, shape, stroke, shadow, and a large number of other features, allowing us to make strange changes to the image. The result of the script we wrote looks like this.
<Canvas> is a JavaScript API, which means we can use all the features of JavaScript variables, events, loops, and so on. Let's apply our scripts to use a simple JavaScript loop to create a small area of the grid in our canvas area.
<Canvas id = "example2" width = "400" height = "300"> </canvas>
// Get the canvas and contextvar canvas = document. getElementById ('example2 ');
Var context = canvas. getContext ('2D '); // orange fill stylecontext. fillStyle =' # ff7700 ';//
Create squares in a loopfor (var x = 0; x <canvas. width; x + = 25) {for (var y = 0; y
<Canvas. height; y + = 25) {context. fillRect (x, y, 20, 20 );}}
In just a few lines of JavaScript, we can generate 192 blocks in our canvas area. In my opinion, this is the true value of <canvas>. It allows us to use the processing capabilities of web browsers to generate mathematical Ry and drawings. Coupled with a little work and a lot of creativity, we can even use this power to achieve artistic effects.
Animation

Before proceeding to this topic, we need to know how to use <canvas> to create an animation. This is a bit harder to do. First, it is easy to use the canvas API in a way that hinders web browser performance. Painting on a canvas requires processor-intensive work, especially if you constantly update drawings like animations. To alleviate any performance questions, I will use a new feature called requestAnimationFrame, which allows our web browser to determine the update frequency of the canvas while maintaining optimal performance in our web file. This is not available in all browsers, but fortunately Paul Ireland once wrote an outstanding poly-fill to add this feature to the old web browser. He wrote this script and web browser in his blog.

For simplicity, I do not intend to include Paul's script in my code example, but you should use it in your own code. Using requestAnimationFrame, we can create a basic "animation loop" in our script ". It looks like this.
<Canvas id = "example3" width = "400" height = "300"> </canvas>
// Get the canvasvar canvas = document. getElementById ('example3'); var context =
Canvas. getContext ('2D '); context. fillStyle =' # ff7700 '; var time = false ;//
Box positionvar x =-100; // animation loopvar loop = function (){//
Get time since last frame var now = new Date (). getTime ();
Var d = now-(time | now); time = now; // clear previusly
Drawn rectangles context. clearRect (0, 0, canvas. width, canvas. height );
// Draw new rectangle context. fillRect (x, 100,100,100 );
// Advance horizontal position x ++ = 0.1 * d;
// Reset horizontal position if (x> canvas. width) {x =-100 ;}//
Request next frame requestAnimationFrame (loop) ;}; // first frameloop ();
When an animation is used in the canvas element, all painting should be completed by a reusable function. In the example, use the loop () function to draw a square on our canvas. The requestAnimationFrame function tells the browser when to automatically select the next frame based on the available processing capabilities. The result is that our loop () function runs over and over again, push our orange box forward from left to right. Please note that we use the d variable (delta) to determine the time between frames, in milliseconds. This is an important addition to make our animation speed normal. Without it, our animation will run faster on a computer with a better processor. After a few years, when the computer gets more processing capabilities, our animation can run faster, to confuse or mislead users. Using the delta variable, we can specify a speed per millisecond. In our example, the position of the square advances by 0.1 * d, or 0.1 pixels per millisecond. After conversion, it is 100 pixels per second. No matter how fast your processor is, animation always takes the same amount of time to complete.
Artistic elements
Now that we understand the canvas element and how to use it to create animations, we can add artistic creativity to create more interesting things. In the next example, we will randomly generate a colored circle in the canvas element and give them a random track. Our "Northern Lights" script becomes vivid by drawing circles rather than solid colors with gradient.
<Canvas id = "example4" width = "400" height = "300" style = "#0e74a2;"> </canvas>
// Get the canvasvar canvas = document. getElementById ('example4'); var context =
Canvas. getContext ('2D '); var time = false; // create an empty array of "circles" var circles
= []; // Animation loopvar loop = function () {// get time since last frame var now = new Date (). getTime ();
Var d = now-(time | now); time = now; // clear the canvas context. clearRect (0, 0, canvas. width,
Canvas. height); // draw circles for (var I = 0; I <circles. length; I ++ ){
Circles [I]. update (d); circles [I]. draw ();} // request next frame requestAnimationFrame (loop );};//
Circle objectvar circle = function (options) {// configuration var circle = this; circle. settings =
{X: 0, y: 0, radius: 20, orientation: 0,
Vector: {x: 0, y: 0}, speed: 1, color: {red: 0, green: 0, blue: 0, alpha: 1 }};
// Merge options into settings var newsettings = {};
For (var attrname in circle. settings) {newsettings [attrname]
= Circle. settings [attrname];} for (var attrname in options) {newsettings [attrname] = options [attrname];}
Circle. settings = newsettings; // update circle. update = function (d) {// update position
Circle. settings. x + = circle. settings. vector. x * circle. settings. speed * d;
Circle. settings. y + = circle. settings. vector. y * circle. settings. speed * d; // bounce
If (circle. settings. x <0 & circle. settings. vector. x <0 | circle. settings. x>
Canvas. width & circle. settings. vector. x> 0 ){

Circle. settings. vector. x = circle. settings. vector. x *-1 ;}

 

If (circle. settings. y <0 & circle. settings. vector. y <0 | circle. settings. y>
Canvas. height & circle. settings. vector. y> 0 ){
Circle. settings. vector. y = circle. settings. vector. y *-1;
}}; // Draw circle. draw = function () {// gradient fill var gradient =
Context. createRadialGradient (circle. settings. x, circle. settings. y,
Circle. settings. radius/10, circle. settings. x, circle. settings. y, circle. settings. radius );
Gradient. addColorStop (0, 'rgba ('+ circle. settings. color. red +', '+ circle. settings. color. green
+ ',' + Circle. settings. color. blue + ',' + circle. settings. color. alpha + ')');
Gradient. addColorStop (1, 'rgba ('+ circle. settings. color. red +', '+ circle. settings. color. green
+ ',' + Circle. settings. color. blue + ',' + circle. settings. color. alpha/50 + ')');
Context. fillStyle = gradient; // draw context. beginPath ();
Context. arc (circle. settings. x, circle. settings. y, circle. settings. radius, 0, 2 * Math. PI, false );
Context. fill () ;};}; // create new circlesvar newcircles = function () {// remove old circles
= []; // Create 5 new circles for (var I = 0; I <5; I ++) {// create a new circle
Var newcircle = new circle ({x: Math. floor (Math. random () * canvas. width ),
Y: Math. floor (Math. random () * canvas. height ),
Radius: Math. floor (Math. random () * canvas. width ),
Orientation: Math. floor (Math. random () * 360 ),
Vector: {x: Math. random ()/40,
Y: Math. random ()/40}, speed: Math. random (),
Color :{
Red: 100 + Math. floor (Math. random () * 155 ),
Green: 100 + Math. floor (Math. random () * 155 ),
Blue: 100 + Math. floor (Math. random () * 155 ),
Alpha: 0.1 + Math. random ()}});
// Add new circle to circles array
Circles. push (newcircle );
}; // Generate new circleswindow. addEventListener ('click', newcircles, false );
Window. addEventListener

('Touchend', newcircles, false); newcircles (); // first frameloop ();

Each time you click in this window, a new random circle will appear.
We have just begun to understand and utilize the power of <canvas>. I am eager to learn how the industry uses it and SVG and other technologies to build amazing and artistic web content. In my next article, I will show you how to use this code to create a simple canvas-based game using keyboard shortcuts and animations, so that you can play this game in a web browser. MoreHTML tutorialIf the video is for you to learn, log on to e Liangshi Yiyou.

 

Create and use the design art of canvas

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.