canvas知识梳理

什么是canvas

  • canvas是html5新增的一个图形绘制元素,经过脚原本完成,一般是用js来绘制。canvas标签只是图形的容器,能够经过canvas来绘制路径、盒、圆、字符及图像。

利用canvas画图的代码示例

1.绘制圆弧html

<template>
	<div class = 'canvas'>
		<canvas id= 'myCanvas' width = '500' height = '500'></canvas>
	</div>
</template>	

<script>
	export default {
    	data(){
        	return {}
	},
    mounted(){
    //获取canvas画布对象
	let myCanvas = document.getElementById('myCanvas');
	//获取画笔
    let ctx = myCanvas.getContext('2d')
    //一、绘制圆弧、圆
	//开启路径
    ctx.beginPath()
    //绘制圆弧
    ctx.arc(200,200,200,0,Math.PI,false)
    //arc的参数为(x,y,r,sAngle,eAngle,是否逆时针)
    //圆心x,y轴坐标,r圆半径,sAngle起始角,eAngle结束角,最有一个是是都为逆时针。
    //关闭路径
    ctx.closePath()
    }
	}
</script>
复制代码

2. 绘制坐标轴html5

<template>
	<div class = 'canvas'>
		<canvas id= 'myCanvas' width = '500' height = '500'></canvas>
	</div>
</template>	

<script>
	export default {
    	data(){
        	return {}
	},
    mounted(){
    //获取canvas画布对象
	let myCanvas = document.getElementById('myCanvas');
	//获取画笔
    let ctx = myCanvas.getContext('2d')
	//开启路径
    ctx.beginPath()
    
    this.line(ctx, 20, 20, 390, 20);
    this.line(ctx, 380, 15, 390, 20);
    this.line(ctx, 380, 25, 390, 20);
    this.line(ctx, 20, 20, 20, 390);
    this.line(ctx, 15, 380, 20, 390);
    this.line(ctx, 25, 380, 20, 390);
    ctx.closePath();
    //设置字体属性
    ctx.font = "20px 楷体";
    //设置字体
    ctx.fillText("坐标轴", 15, 15);
    ctx.fillText("x轴", 370, 40);
    ctx.fillText("y轴", 30, 385);
    //关闭路径
    ctx.closePath()
    },
    methods:{
    	line(ctx,sx,sy,ex,ey){
    		ctx.moveTo(sx,sy)
            ctx.lineTo(ex,ey)
            ctx.stroke()
    	}
    }
	}
</script>
复制代码
  1. 绘制矩形
//描边矩形
ctx.strokeRect(40,40,100,100)
//矩形的起始点为x轴40,y轴40,宽100,高100
//填充矩形
ctx.fillRect(140,140,100,100)
复制代码
  1. 弧度和角度的相转换
//角度转弧度
function toRad(angle){
	return angle*Math.PI/180
}
//弧度转角度
function toAngle(rad){
	return rad*180/Math.PI
}
复制代码
  1. 获取鼠标在元素上的坐标
let C = {}
    let canvas = document.getElementById("myCanvas");
    C.getOffset = function (ele) {
        let mouse = { x: 0, y: 0 }
        ele.addEventListener('mousemove', function (e) {
            let { x, y } = C.eventWrapper(e)
            mouse.x = x;
            mouse.y = y;
        })
        return mouse
    }
    //坐标系的转换
    C.eventWrapper = function (ev) {
        let { pageX, pageY, target } = ev
        console.log(target)
        let { left, top } = target.getBoundingClientRect();
        return { x: pageX - left, y: pageY - top }
    }
    let pot = C.getOffset(canvas)
    canvas.onclick = function () {
        console.log(pot)
    }
复制代码
相关文章
相关标签/搜索