canvas画图

954 阅读1分钟

1.canvas简单画图

1.1初始化简单的canvas画布

<canvas id="canvas" width="200px" height="200px" ref="canvas" style="border: 1px solid #999;"></canvas>

// 获取canvas元素
this.canvas = document.getElementById('tutorial')
// 获取绘制二维上下文
this.ctx = this.canvas.getContext('2d')

1.2在画布上画简单的图形

image.png

        // 开始绘制图形  简单的直线
        ctx3.moveTo(50, 150)
        ctx3.lineTo(150, 50)
        ctx3.stroke()

1.3canvas 画矩形(strokeReact 为描边, fillReact 为填充矩形)

image.png

// canvas 画矩形有两种常见的方式,
// 1 直接使用直线去画
    this.ctx.moveTo(150, 50)
    this.ctx.lineTo(150, 150)
    this.ctx.lineTo(50, 150)
    this.ctx.lineTo(150, 50)
    this.ctx.strokeStyle = "#999999"
    this.ctx.stroke()
    
// 2 使用canvas 提供的方法react
this.ctx.strokeStyle = "#ff0000"
this.ctx.strokeRect(50, 50, 200, 200)

1.4 根据三角函数画正多边形(也可以画圆)

image.png

    // 多边形封装函数
    createPolygon(ctx, n, dx, dy, size) {
            ctx.beginPath()
            let degree = (2 * Math.PI)/n
            for(var i = 0; i< n; i++) {
                let x = Math.cos(i * degree)
                let y = Math.sin(i * degree)
                console.log(x*size + dx, y * size + dy)
                ctx.lineTo(x*size + dx, y * size + dy)
            }
            ctx.closePath()
        }
    // 调用方法 (当 n > 60 基本上就是一个圆了)
    this.ctx.fillStyle = 'HotPink'
        this.createPolygon(this.ctx, 3, 100, 100, 60)
        this.ctx.fill()
        this.ctx.stroke()

1.5 画一个圆

image.png

// 画圆 arc() x 左边 Y 坐标 半径 开始角度 结束角度 是否是顺时针方向画
this.ctx.beginPath()
            this.ctx.arc(100, 100, 50, 0*Math.PI/180, 360*Math.PI/180, true)
            this.ctx.closePath()
            this.ctx.fillStyle = "HotPink"
            this.ctx.fill()
            
// 画一个扇形
 this.ctx.beginPath()
            this.ctx.arc(100, 100, 50, 0*Math.PI/180, 60*Math.PI/180, true)
            this.ctx.closePath()
            this.ctx.fillStyle = "HotPink"
            this.ctx.fill()

1.6 结合以上学过的画一个简单的饼状图

image.png

count: [30, 60, 50, 90, 60, 70],
colors: ['#eeeeee', 'HotPink', 'red', 'green', 'blue', '#d4d4d5']

if(this.count && this.count.length > 0) {
                let allcount = this.count.reduce((a, b) => {
                    return a + b
                })
                let newdegree = 0
                this.count.forEach((p, index) => {
                    if(index < 6) {
                        this.ctx.beginPath()
                        this.ctx.moveTo(100, 100)
                        let jd = p/allcount * 2 * Math.PI
                        this.ctx.arc(100, 100, 50, newdegree, jd + newdegree, false)
                        this.ctx.closePath()
                        this.ctx.fillStyle = this.colors[index]
                        this.ctx.fill()
                        newdegree += jd
                    }
                })
            }