Canvas basic learning (3): canvas basic learning

Source: Internet
Author: User

Canvas basic learning (3): canvas basic learning

I. image loading controls

Multiple images are often used in canvas effect creation. To improve the user experience, you need to provide users with excessive page effects during image loading. I used Sonic. js in the project, and its address on git is. Is:

The call code is also relatively simple.

<script type="text/javascript" src="js/sonic.js"></script><script>            var loading = new Sonic({                width: 100,                height: 100,                stepsPerFrame: 1,                trailLength: 1,                pointDistance: .1,                fps: 15,                padding: 10,                fillColor: '#fff',                setup: function() {                    this._.lineWidth = 20;                },                path: [                    ['line', 0, 20, 100, 20],                    ['line', 100, 20, 0, 20]                ]            });            loading.play();            document.body.appendChild(loading.canvas);        </script>

The following is a self-written image loading Tool

(Function (window, undefind) {// function imgLoad (options) {var defaults = {imgArr: [], // loadOverCallback: null // callback function after loading}; var opts = $. extend (true, defaults, options | |{}), imgSize = opts. imgArr. length, // The number of images to be loaded completeSize = 0; function beginLoad () {for (var index in opts. imgArr) {var src = opts. imgArr [index]; src & loadImg (src) ;}} function loadImg (src) {// load image va R image = new Image (), handleLoadOver = function () {completeSize ++; checkLoadOver () ;}; image. src = src; if (image. complete) {// handleLoadOver ();} else {image. onload = function () {// The image is obtained successfully. handleLoadOver () ;}}} function checkLoadOver () {// query whether the load has been completed if (completeSize! = ImgSize) return; if (opts. loadOverCallback & typeof opts. loadOverCallback = "function") {opts. loadOverCallback () ;}} beginLoad () // start execution} window. imgLoad = imgLoad;}) (window );

The logic of the code is to input the Image url to be loaded in the form of an array, and then load it through the new Image () object. Each time the loading is complete, a function is executed to check whether the loading is complete, when all images are loaded, the end callback function is executed. The call method is as follows:

Window. imgLoad ({imgArr: ["img/1.jpg"," img/2.jpg", "img/3.jpg"," img/4.jpg", "img/5.jpg"], loadOverCallback: function () {// end operation ....}});

 

2. specify the effects of snow, ribbons, and stars on Elements

 

(Function (window, document, undefind) {// canvas special effect function canvasEffect (options) {var defaults = {ele: document. getElementById ("body"), // cover element type: "snow", // snow is snowflake, band is color band, star is star particle MAX: 200, // maximum number of elements: 100, // use the number of elements bandColorArr: ["#82F269", "# F61326", "# F6F313", "#518DF6"], // The color array vy: 1, // The motion speed vyFloat: 1.5 on the Y axis, // The coefficient of the Y axis Speed Fluctuation vx: 0.5, // The motion speed on the X axis vxFloat: 1, // X-axis speed floating coefficient w: 8, // element width wFloat: 2, // width floating coefficient h: 12, // element height hFloat: 4, // floating coefficient of height o: 0.4, // transparency of elements oFloat: 0.5, // floating coefficient of transparency r: 1, // radius rFloat: 2, // floating value of the radius snowColor: "# FFF" // snowflake color} var opts = $. extend (true, defaults, options | |{}); var canvas = document. createElement ('canvas '), ctx = canvas. getContext ('2d '), width = opts. ele. clientWidth, height = opts. ele. clientHeight, I = 0, Active = false, objFlakes = [], objFlake, lastDate = 0, dateDel = 0, isChange = false; var starPic = new Image (); starPic. src = "img/star.png"; canvas. style. position = 'absolute '; canvas. style. left = canvas. style. top = '0'; var Objflake = function () {this. reset (); // initialization}; Objflake. prototype. reset = function () {this. x = Math. random () * width; this. y = Math. random () *-height; this. vy = opt S. vy + Math. random () * opts. vyFloat; this. vx = opts. vx-Math. random () * opts. vxFloat; this. w = opts. w + Math. random () * opts. wFloat; this. h = opts. h + Math. random () * opts. hFloat; this. o = opts. o + Math. random () * opts. oFloat; this. color = opts. bandColorArr [parseInt (Math. random () * opts. bandColorArr. length)]; this. c = Math. random ()> 0.5? 1:-1; this. r = opts. r + Math. random () * opts. rFloat; this. picNo = Math. floor (Math. random () * 7) ;}; function generatebandFlakes () {// Number of initialization elements objFlakes = []; for (I = 0; I <opts. particle Max; I ++) {objFlake = new Objflake (); objFlake. reset (); objFlakes. push (objFlake) ;}} function update () {// update ctx. clearRect (0, 0, width, height); if (! Active) {return;} if (opts. type = "star") {var nowDate = Date. now (); dateDel + = nowDate-lastDate; lastDate = nowDate; isChange = (dateDel> 60); if (isChange) {dateDel = 0 ;}} for (I = 0; I <opts. particle count; I ++) {objFlake = objFlakes [I]; objFlake. y + = objFlake. vy; objFlake. x + = objFlake. vx; if (opts. type = "snow") {drawSnow (objFlake. x, objFlake. y, objFlake. r, objFlake. o);} else if (opts. t Ype = "band") {drawBand (objFlake. x, objFlake. y, objFlake. color, objFlake. w, objFlake. h, objFlake. c, objFlake. o);} else if (opts. type = "star") {if (isChange) {objFlake. picNo + = 1; objFlake. picNo = objFlake. picNo % 7;} ctx. drawImage (starPic, objFlake. picNo * 7, 0, 7, 7, objFlake. x, objFlake. y, 7, 7);} if (objFlake. y> height) {objFlake. reset () ;}} requestAnimFrame (update) ;}// color belt function drawBa Nd (x, y, color, w, h, c, alpha, isRotate, rotatePI) {var leakdep = h <10? 2: 8; var leak = c> 0? Leakdep:-(leakdep); ctx. save (); ctx. fillStyle = color; ctx. globalAlpha = alpha; ctx. beginPath (); ctx. moveTo (x, y-h); ctx. lineTo (x + w, y-h); ctx. quadraticCurveTo (x + w + c, y-h/2, x + w + leak, y); ctx. lineTo (x + leak, y); ctx. quadraticCurveTo (x + c, y-h/2, x, y-h); ctx. fill (); ctx. closePath (); ctx. restore ();} // draw snowflake function drawSnow (x, y, r, o) {ctx. save (); ctx. fillStyle = opt S. snowColor; ctx. globalAlpha = o; ctx. beginPath (); ctx. arc (x, y, r, 0, Math. PI * 2, false); ctx. fill (); ctx. closePath (); ctx. restore ();} function onResize () {width = opts. ele. clientWidth; height = opts. ele. clientHeight; canvas. width = width; canvas. height = height; lastDate = Date. now (); var wasActive = active; active = width & gt; 300; if (! WasActive & active) {requestAnimFrame (update) ;}} window. requestAnimFrame = (function () {return window. requestAnimationFrame | window. webkitRequestAnimationFrame | window. required requestanimationframe | function (callback) {window. setTimeout (callback, 1000/60) ;};} (); generatebandFlakes (); onResize (); opts. ele. appendChild (canvas); window. addEventListener ('resize', onResize, false);} window. canvasEffect = canvasEffect;}) (window, document );

The code above indicates that the logic is to create a canvas label on the specified ele element. The height and width are the same as those of the ele element. a snowflake, color band, or star image is drawn on the canvas, based on the animation function requestAnimationFrame and the pre-defined x and y-axis speed, draw a frame by frame. The x and y coordinates of each frame change to produce the animation effect. The star image is

The call method is as follows:

1. Stars

window.canvasEffect({            ele : document.getElementsByTagName("body")[0] ,              type : "star" ,             particleMax : 300 ,                 particleCount : 150 ,            vy : 0.3 ,            vyFloat : 0.3 ,                    vx : 0.3 ,                vxFloat : 0.6 ,                    o : 0.3 ,            oFloat : 0.3 ,            });

Is:

 

2. Ribbons

window.canvasEffect({            ele : $("body")[0] ,              type : "band" ,             particleMax : 200 ,                 particleCount : 100 ,            bandColorArr : ["#82F269", "#F61326", "#F6F313", "#518DF6"] ,             w : 8 ,             wFloat : 2 ,                 h : 12 ,             hFloat : 4 ,             o : 0.4 ,            oFloat : 0.5 ,                r : 1 ,                rFloat : 2            });

Is:

 

3. Snowflake

window.canvasEffect({            ele : $("body")[0] ,              type : "snow" ,             particleMax : 200 ,                 particleCount : 100 ,            o : 0.4 ,            oFloat : 0.5 ,                r : 1 ,                rFloat : 2            });

Is:

 

Related Article

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.