美文网首页
canvas基础入门实例

canvas基础入门实例

作者: LElysion | 来源:发表于2017-10-27 19:50 被阅读0次

核心思想

通过不断地刷新当前帧, 获得动画效果

canvas标签

canvas是html5的一个标签, 有两个属性width和height, 在js中调用的时候一般使用document.getElementById('canvas').width来获取或设置

了解canvas

canvas中所有的渲染行为都是基于javascript的, 也就是说只需要编写相应的javascript便可以获得相应的效果, 在绘制一些静态的基本形状, 文字或图片的时候,可以非常简单,不过这样的事情根本不需要使用到canvas, canvas真正让人着迷的是其动态效果
canvas的动态效果可以做到十分神奇,而且是基于javascript操作单一元素, 所以不需要考虑到重排, 只需要重绘本身即可,在效率上远比css3等要高

canvas动画原理

动画是由多帧静态图片做切换而欺骗人的眼睛完成的, 而canvas本身就是一块画布, 所以在javascript中就可以通过编写自己想要的动画从而完成动画效果
基本的核心便是不断的重绘当前帧即可

完成简单的动画的步骤

  1. 编写动画的对象
/**
 * 构造函数
 * @param {boolean} animated 当前是否运动中
 * @param {number} x 生成坐标x
 * @param {number} y 生成坐标y
 * @param {number} vx x轴偏移速度
 * @param {number} vy y轴偏移速度
 * @param {number} radius 圆本身的角度
 * @param {array} color 颜色
 * @param {number} time 运动持续时间
 */
function Circle(x, y, vx, vy, radius, color, time){
    this.animated = true
    this.x = x;
    this.y = y;
    this.vx = vx;
    this.vy = vy;
    this.radius = radius;
    this.time = time;
    this.color = ['LightPink', 'PaleVioletRed', 'DeepPink', 'MediumVioletRed', 
    'Magenta', 'DarkVoilet', 'SlateBlue','Navy', 
    'RoyalBlue', 'DarkSlateGray', 'Auqamarin', 'MintCream', 
    'Olive', 'Gold','Tomato', 'Red'];
    this.globalAlpha = 1;//透明度
    this.vglobalAlpha  = 0.02;//透明渐变
}

/**创建对象数组
 * @param {number} x 鼠标当前位置x
 * @param {number} y 鼠标当前位置y 
 * @return {array} 一组带有圆的参数的对象数组
 */
Circle.prototype.create = function(x, y) {
    iscreate = false;
    var _this = this;
    var n = _this.random(20, 30);//渲染数量
    var circles = [];//放入
    for(var i=0; i<n; i++){
        var imgsize = parseInt(6+_this.random(0, 12))
        circles[i] = {
            x: parseInt(x+_this.random(-32, 32)),//坐标
            y: parseInt(y+_this.random(-32, 32)),//坐标
            vx: _this.random(-1.2, 1.2),//偏移量
            vy: _this.random(-1.2, 1.2),//偏移量
            radius: parseInt(2+_this.random(0, 6)),//半径
            startAngle: 0,//开始弧度
            endAngel: Math.PI*2,//结束弧度
            anticlockwise: true,//逆时针, false:顺时针
            color:_this.color[parseInt(_this.random(0, 16))],
            i: i,//数组中的位置,
            globalAlpha: _this.globalAlpha*Math.random(),
        }
    }
    _this.draw(circles, n);
    return circles;
}

在这里先定义一个圆的构造函数,里边声明了所需要的一个圆的属性,包括生成坐标,偏移速度等,因为该例子需要渲染多个圆,所以写了一个数组来装载圆的对象,非常简单, 不过这里是复杂动画的起步, 越复杂的动画所需要的参数便是越多,这方面可以自己编写,完全的可声明,可定义。

  1. 将静态对象放入到canvas里边,即绘制第一帧
/**
 * 绘制圆
 * @param {array} circles 圆的对象数组
 */
Circle.prototype.draw = function(circles, n){
    var _this = this;
    for(var i=0; i<circles.length; i++) {
        //ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise)
        //绘制圆
        ctx.beginPath();
        ctx.arc(circles[i].x, circles[i].y, circles[i].radius, circles[i].startAngle,circles[i].endAngel,circles[i].anticlockwise);
        ctx.closePath();
        ctx.fillStyle = circles[i].color;//circles[i].color;
        ctx.globalAlpha = circles[i].globalAlpha;
        ctx.fill();
    }
    _this.animate(circles);
}

在这里将你的圆全部放入到canvas里面, 使用的是一个封装好的随机函数, 实际上你需要其他初始化方式同样也可以自定义,因为是使用javascript, 所以高度可定制

  1. 动画效果
/**
 * 添加偏移动画
 * @param {array} circles 圆的对象数组
 */
Circle.prototype.animate = function( circles ) {
    var _this = this;
    window.cancelAnimationFrame(timer);
    timer = window.requestAnimationFrame(function(){
        _this.clearCanvas();
        for(var i=0; i<circles.length; i++){
            circles[i].vx += 0.01;
            circles[i].vy += 0.01;
            circles[i].x += circles[i].vx;
            circles[i].y += circles[i].vy;//增加偏移量
            circles[i].globalAlpha -= _this.vglobalAlpha;//设置透明度
        }
        _this.draw(circles);
    })
}

这里是用于绘制下一帧的方法,这里主要是将上一帧的圆的坐标稍微偏移再将其重新渲染出来完成的,在渲染速度足够的情况下, 可以很简单的就完成一个动画效果

  1. 用户交互
//canvas事件
function mousedown(event) {
    var ex = event.point.x;//获取当前鼠标所在区域
    var ey = event.point.y;//获取当前鼠标所在区域
    window.cancelAnimationFrame(timer);
    c.create(ex, ey);
}

这里绑定事件即可

附录

index.html

<canvas id="canvas"></canvas>

canvas_circle.js

//canvas_circle.js
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var timer;//定时器

/**
 * 构造函数
 * @param {boolean} animated 当前是否运动中
 * @param {number} x 生成坐标x
 * @param {number} y 生成坐标y
 * @param {number} vx x轴偏移速度
 * @param {number} vy y轴偏移速度
 * @param {number} radius 圆本身的角度
 * @param {array} color 颜色
 * @param {number} time 运动持续时间
 */
function Circle(x, y, vx, vy, radius, color, time){
    this.animated = true
    this.x = x;
    this.y = y;
    this.vx = vx;
    this.vy = vy;
    this.radius = radius;
    this.time = time;
    this.color = ['LightPink', 'PaleVioletRed', 'DeepPink', 'MediumVioletRed', 
    'Magenta', 'DarkVoilet', 'SlateBlue','Navy', 
    'RoyalBlue', 'DarkSlateGray', 'Auqamarin', 'MintCream', 
    'Olive', 'Gold','Tomato', 'Red'];
    this.fps = 60;//帧数
    this.globalAlpha = 1;//透明度
    this.vglobalAlpha  = 0.02;//透明渐变
}

/**
 * 返回随机数
 * @param {number} min最小值
 * @param {number} max最大值
 * @return {number}
 */
Circle.prototype.random = function( min, max ){
    return Math.random() * (max - min) + min;
}

//初始化
Circle.prototype.init = function() {
    this.render();
    //this.draw();
}

//渲染canvas
Circle.prototype.render = function() {
    canvas.width = window.innerWidth - 1;
    canvas.height = window.innerHeight - 1;
}

/**创建对象数组
 * @param {number} x 鼠标当前位置x
 * @param {number} y 鼠标当前位置y 
 * @return {array} 一组带有圆的参数的对象数组
 */
Circle.prototype.create = function(x, y) {
    iscreate = false;
    var _this = this;
    var n = _this.random(20, 30);//渲染数量
    var circles = [];//放入
    for(var i=0; i<n; i++){
        var imgsize = parseInt(6+_this.random(0, 12))
        circles[i] = {
            x: parseInt(x+_this.random(-32, 32)),//坐标
            y: parseInt(y+_this.random(-32, 32)),//坐标
            vx: _this.random(-1.2, 1.2),//偏移量
            vy: _this.random(-1.2, 1.2),//偏移量
            radius: parseInt(2+_this.random(0, 6)),//半径
            startAngle: 0,//开始弧度
            endAngel: Math.PI*2,//结束弧度
            anticlockwise: true,//逆时针, false:顺时针
            color:_this.color[parseInt(_this.random(0, 16))],
            i: i,//数组中的位置,
            globalAlpha: _this.globalAlpha*Math.random(),
        }
    }
    _this.draw(circles, n);
    return circles;
}

/**
 * 绘制圆
 * @param {array} circles 圆的对象数组
 */
Circle.prototype.draw = function(circles, n){
    var _this = this;
    for(var i=0; i<circles.length; i++) {
        //ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise)
        //绘制圆
        ctx.beginPath();
        ctx.arc(circles[i].x, circles[i].y, circles[i].radius, circles[i].startAngle,circles[i].endAngel,circles[i].anticlockwise);
        ctx.closePath();
        ctx.fillStyle = circles[i].color;//circles[i].color;
        ctx.globalAlpha = circles[i].globalAlpha;
        ctx.fill();
    }
    _this.animate(circles);
}


/**
 * 添加偏移动画
 * @param {array} circles 圆的对象数组
 */
Circle.prototype.animate = function( circles ) {
    var _this = this;
    window.cancelAnimationFrame(timer);
    timer = window.requestAnimationFrame(function(){
        _this.clearCanvas();
        for(var i=0; i<circles.length; i++){
            circles[i].vx += 0.01;
            circles[i].vy += 0.01;
            circles[i].x += circles[i].vx;
            circles[i].y += circles[i].vy;//增加偏移量
            circles[i].globalAlpha -= _this.vglobalAlpha;//设置透明度
        }
        _this.draw(circles);
    })
}

/**
 * @method 清空canvas
 */
Circle.prototype.clearCanvas = function() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
}

//动画开始及结束
canvas.addEventListener('mouseover', function(){
    //raf = window.requestAnimationFrame(draw);
})
canvas.addEventListener('mouseout', function(){
    //window.cancelAnimationFrame(raf);
})

var c = new Circle();
c.init();

//canvas事件
function mousedown(event) {
    var ex = event.point.x;//获取当前鼠标所在区域
    var ey = event.point.y;//获取当前鼠标所在区域
    window.cancelAnimationFrame(timer);
    c.create(ex, ey);
}
function mousemove(event) {
    //document.querySelector('.pointX1').innerHTML = event.point.x;
    //document.querySelector('.pointY1').innerHTML = event.point.y;
}
function mouseup(event) {
    var ex = event.point.x;//获取当前鼠标所在区域
    var ey = event.point.y;//获取当前鼠标所在区域
}

tool.captureMT(canvas, mousedown, mousemove, mouseup);

canvas_tool.js

//canvas_tool.js
window.tool = {};   
window.tool.captureMT = function(element, touchStartEvent, touchMoveEvent, touchEndEvent) {   
    'use strict';   
    var isTouch = ('ontouchend' in document);   
    var touchstart = null;   
    var touchmove = null   
    var touchend = null;   
    if(isTouch){   
      touchstart = 'touchstart';   
      touchmove = 'touchmove';   
      touchend = 'touchend';   
    }else{   
      touchstart = 'mousedown';   
      touchmove = 'mousemove';   
      touchend = 'mouseup';   
    };   
  
    /*传入Event对象*/   
    function getPoint(event) {   
      /*将当前的触摸点坐标值减去元素的偏移位置,返回触摸点相对于element的坐标值*/     event = event || window.event;
      var touchEvent = isTouch ? event.changedTouches[0]:event;
      var x = (touchEvent.pageX || touchEvent.clientX + document.body.scrollLeft + document.documentElement.scrollLeft);   
      x -= element.offsetLeft;   
  
      var y = (touchEvent.pageY || touchEvent.clientY + document.body.scrollTop + document.documentElement.scrollTop);   
      y -= element.offsetTop;   
  
      return {x: x,y: y};
    };
    if(!element) return;   
    /*为element元素绑定touchstart事件*/   
    element.addEventListener(touchstart, function(event) {   
      event.point = getPoint(event);   
      touchStartEvent && touchStartEvent.call(this, event);   
    }, false);    
  
    /*为element元素绑定touchmove事件*/   
    element.addEventListener(touchmove, function(event) {   
      event.point = getPoint(event);   
      touchMoveEvent && touchMoveEvent.call(this, event);   
    }, false);    
  
    /*为element元素绑定touchend事件*/   
    element.addEventListener(touchend, function(event) {   
      event.point = getPoint(event);   
      touchEndEvent && touchEndEvent.call(this, event);   
    }, false);   
  };

相关文章

  • canvas基础入门实例

    核心思想 通过不断地刷新当前帧, 获得动画效果 canvas标签 canvas是html5的一个标签, 有两个属性...

  • 我的战舰地图逻辑教程

    基础知识 - 简书 实例讲解-推箱子(入门) 实例讲解-打Boss(入门) - 简书 实例讲解-弹球(进阶) - 简书

  • canvas 基础入门

    是什么 Canvas(画布)是在 HTML5 中新增的标签用于在网页实时生成图像,可以操作图像内容,是一个可以用 ...

  • canvas实例

    使用原生canvas做钟表实例 使用canvas库做钟表实例 太阳系实例

  • canvas入门基础2

    继canvas入门基础1 _ 圆弧context.arc(x, y, radius, start,end, boo...

  • canvas实现时钟效果

    HTML5的canvas的实用入门小实例,一步步一起来。学习的最好方法就是实践,参考HTML 5 Canvas 参...

  • 10分钟从入门到进阶python爬虫

    本文目录 基础入门 基本模块 方法实例 爬虫框架(scrapy) 常用工具(神器) 分布式爬虫 一、基础入门 1....

  • canvas入门基础1

    canvas即一个H5的新标签,通过js来实现绘图的神奇功能。 注意,在这里我直接在行间设置了宽高,是因为若不设定...

  • canvas入门-小时钟

    canvas入门-小时钟

  • java类class和对象object,构造方法

    构造方法实例代码,出处:java 基础入门(二)_man_zuo的博客-CSDN博客

网友评论

      本文标题:canvas基础入门实例

      本文链接:https://www.haomeiwen.com/subject/phudpxtx.html