canvas

canvas 元素使用 JavaScript 在网页上绘制图像。它拥有多种绘制路径、矩形、圆形、字符以及添加图像的方法。

 <canvas id="myCanvas" width="600" height="400"></canvas>

canvas的宽高使用行内样式设置,在style中设置宽高会使画布中的元素失去自己真实的px大小。

方法:

getContext() 方法可返回一个对象,该对象提供了用于在画布上绘图的方法和属性。
getContext(“2d”) 对象属性和方法,可用于在画布上绘制文本、线条、矩形、圆形等

路径

方法描述
fill()填充当前绘图(路径)
stroke()绘制已定义的路径
beginPath()起始一条路径,或重置当前路径
moveTo(x,y)把路径移动到画布中的指定点,不创建线条
closePath()创建从当前点回到起始点的路径
lineTo(x,y)添加一个新点,然后在画布中创建从该点到最后指定点的线条
clip()从原始画布剪切任意形状和尺寸的区域
quadraticCurveTo(控制点的 x,控制点的 y,结束点的 x,结束点的 y)创建二次贝塞尔曲线
bezierCurveTo(控制点1的 x,控制点1的 y,控制点2的 x,控制点2的 y,结束点的 x,结束点的 y)创建三次方贝塞尔曲线
arc(x0,y0,radius,starAngle,endAngle,False = 顺时针(默认)/true = 逆时针)创建弧/曲线(用于创建圆形或部分圆)
arcTo(starX,satrY,endX,endY,r)创建两切线之间的弧/曲线
isPointInPath()如果指定的点位于当前路径中,则返回 true,否则返回 false

颜色、样式和阴影

属性描述
fillStyle设置或返回用于填充绘画的颜色、渐变或模式
strokeStyle设置或返回用于笔触的颜色、渐变或模式
shadowColor设置或返回用于阴影的颜色
shadowBlur设置或返回用于阴影的模糊级别
shadowOffsetX设置或返回阴影距形状的水平距离
shadowOffsetY设置或返回阴影距形状的垂直距离

线条样式

属性描述
lineCap设置或返回线条的结束端点样式
lineJoin设置或返回两条线相交时,所创建的拐角类型
lineWidth设置或返回当前的线条宽度
miterLimi设置或返回最大斜接长度

矩形

方法描述
rect(x,y,w,h)创建矩形
fillRect(x,y,w,h)绘制“被填充”的矩形
strokeRect(x,y,w,h)绘制矩形(无填充)
clearRect(x,y,w,h)在给定的矩形内清除指定的像素

文本

方法描述
fillText(text,x,y,[maxWidth])在画布上绘制“被填充的”文本
strokeText(text,x,y,[maxWidth])在画布上绘制文本(无填充)
measureText(text)返回包含指定文本宽度的对象,measureText(text).width
属性描述
font设置或返回文本内容的当前字体属性
textAlign设置或返回文本内容的当前对齐方式,center|end|left|right|start
textBaseline设置或返回在绘制文本时使用的当前文本基线,alphabetic|top|hanging|middle|ideographic|bottom

其他:
save() 保存当前环境的状态
restore() 返回之前保存过的路径状态和属性

案例1:面向对象的方式绘制折线图
在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<canvas height="400" width="600" style="border: 1px solid #eeeeee"></canvas>
<script>
    function LineCart(ctx, gridSize) {
        this.ctx = ctx || document.querySelector('canvas').getContext('2d');
        this.w = this.ctx.canvas.width;
        this.h = this.ctx.canvas.height;
        //网格间距
        this.gridSize = gridSize || 10;
        //坐标系
        this.space = 20;//画布与xy轴之间的间距
        this.x0 = this.space;
        this.y0 = this.h - this.space;

        this.arrowSize = 10;//箭头的大小
        this.pointSize = 6;//点的大小
    }

    LineCart.prototype.init = function () {
        this.drawGrid();
        this.drawAxis();
        this.drawPoint();
    }
    //绘制网格
    LineCart.prototype.drawGrid = function () {
        //x轴
        var xLine = Math.floor(this.h / this.gridSize);
        this.ctx.strokeStyle = '#eee';
        for (var i = 0; i < xLine; i++) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, i * this.gridSize - 0.5);
            this.ctx.lineTo(this.w, i * this.gridSize - 0.5);
            this.ctx.stroke();
        }
        //y轴
        var yLine = Math.floor(this.w / this.gridSize);
        for (var i = 0; i < yLine; i++) {
            this.ctx.beginPath();
            this.ctx.moveTo(i * this.gridSize - 0.5, 0);
            this.ctx.lineTo(i * this.gridSize - 0.5, this.h);
            this.ctx.stroke();
        }

    }
    //坐标系
    LineCart.prototype.drawAxis = function () {
        //x轴
        this.ctx.beginPath();
        this.ctx.moveTo(this.x0,this.y0-0.5);
        this.ctx.lineTo(this.w-this.space,this.y0-0.5);
        this.ctx.lineTo(this.w-this.space-this.arrowSize,this.y0+this.arrowSize/2-0.5);
        this.ctx.lineTo(this.w-this.space-this.arrowSize,this.y0-this.arrowSize/2-0.5);
        this.ctx.lineTo(this.w-this.space,this.y0-0.5);
        this.ctx.fill();
        this.ctx.strokeStyle='#000';
        this.ctx.stroke();

        //y轴
        this.ctx.beginPath();
        this.ctx.moveTo(this.x0-0.5,this.y0);
        this.ctx.lineTo(this.x0-0.5,this.space);
        this.ctx.lineTo(this.x0-this.arrowSize/2-0.5,this.space+this.arrowSize);
        this.ctx.lineTo(this.x0+this.arrowSize/2-0.5,this.space+this.arrowSize);
        this.ctx.lineTo(this.x0-0.5,this.space);
        this.ctx.fill();
        this.ctx.stroke();
    }
    //绘制点并连接
    LineCart.prototype.drawPoint = function () {
         this.ctx.beginPath();
         this.ctx.moveTo(this.x0,this.y0);
         data.forEach(function (item,index) {
             var x=item.x+this.x0;
             var y=this.y0-item.y;
             this.ctx.fillRect(item.x+this.x0-this.pointSize/2,this.y0-item.y-this.pointSize/2,this.pointSize,this.pointSize);
             this.ctx.lineTo(x,y);
             this.ctx.stroke();
         }.bind(this));

    }

    var data=[{x:100,y:100}, {x:200,y:140},{x:300,y:300},{x:400,y:260},{x:500,y:350} ];
    var lineCart = new LineCart();
    lineCart.init();
</script>
</body>
</html>

案例2:面向对象的方式绘制饼状图
在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<canvas width="600" height="400" style="border: 1px solid #F3F3F3"></canvas>
<script>
    var ctx = document.querySelector('canvas').getContext('2d');

    var data = [
        {title: "20岁以下", num: 15},
        {title: "20-25岁", num: 25},
        {title: "25-30岁", num: 30},
        {title: "30-40岁", num: 25},
        {title: "40岁以上", num: 10}
    ];


    function PicChart() {
        this.ctx = document.querySelector('canvas').getContext('2d');
        this.w = this.ctx.canvas.width;
        this.h = this.ctx.canvas.height;
        //圆心
        this.x0 = this.w / 2 + 60;
        this.y0 = this.h / 2;
        //半径
        this.radius = 150;
        //伸出的线
        this.outline = 20;
        //说明文字前的矩形宽度与高度
        this.rectW=30;
        this.rectH=20;
        //说明文字前矩形之间的间隔
        this.space=10;
    }

    PicChart.prototype.init = function () {
        this.drawPic();
    }
    // 绘制饼图
    PicChart.prototype.drawPic = function () {
        var angleList = this.draeAngle();
        var startAngle = 0;
        angleList.forEach(function (item, index) {
            var endAngle = startAngle + item.angle;
            this.ctx.beginPath();
            this.ctx.moveTo(this.x0, this.y0);
            this.ctx.arc(this.x0, this.y0, this.radius, startAngle, endAngle);
            this.ctx.closePath();
            var color = this.ctx.fillStyle = this.randomCorlor();
            this.ctx.fill();
            //调用绘制标题
            this.drawTitle(startAngle, item.angle, color,item.title);
            //绘制矩形说明文字
            this.drawDesc(item.title,color,index);
            //存储下一个扇形的开始弧度
            startAngle = endAngle;
        }.bind(this))

    }
    // 绘制标题
    PicChart.prototype.drawTitle = function (startAngle, angle, color,title) {
        //确定伸出去的点,通过三角函数确定邻边与对边
        var edge = this.radius+this.outline;//斜边
        var edgeX = edge * Math.cos(startAngle + angle / 2);//邻边
        var edgeY = edge * Math.sin(startAngle + angle / 2);// 对边

        var outX = this.x0 + edgeX;
        var outY = this.y0 + edgeY;

        this.ctx.beginPath();
        this.ctx.moveTo(this.x0, this.y0);
        this.ctx.lineTo(outX, outY);
        this.ctx.strokeStyle = color;

        // 文字与线划线
        this.ctx.font='14px 微软雅黑';
        var textWidth=this.ctx.measureText(title).width;
        if (outX>this.x0){
            //相对圆点 右边
            this.ctx.lineTo(outX+textWidth,outY);
            this.ctx.textAlign='left';
        }else {
            //相对圆点 左边
            this.ctx.lineTo(outX-textWidth,outY);
            this.ctx.textAlign='right';
        }
        this.ctx.fillText(title,outX,outY-5);
        this.ctx.textBaseline='bottom';
        this.ctx.stroke();

    }
    // 绘制饼图说明
    PicChart.prototype.drawDesc = function (title,color,index) {
        this.ctx.fillStyle=color;
        var x=20;
        var y=this.space+(this.space+this.rectH)*index;
        this.ctx.fillRect(x,y,this.rectW,this.rectH);
        this.ctx.textAlign='left';
        this.ctx.textBaseline='middle';
        this.ctx.fillText(title,x+this.rectW+10,y+this.rectH/2);
    }

    //将数据转为弧度
    PicChart.prototype.draeAngle = function () {
        var total = 0;
        data.forEach(function (item, index) {
            total += item.num;
        });
        data.forEach(function (item, index) {
            var angle = item.num / total * 2 * Math.PI;
            //将angle放入对象
            item.angle = angle;
        })
        return data;
    }
    //设置随机颜色

    PicChart.prototype.randomCorlor = function () {
        var r = Math.floor(Math.random() * 256);
        var g = Math.floor(Math.random() * 256);
        var b = Math.floor(Math.random() * 256);
        return 'rgb(' + r + ',' + g + ',' + b + ')';
    }

    var picChart = new PicChart();
    picChart.init();

</script>

</body>
</html>

分析图:
分析图

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值