Canvas draws any polygon

Call to draw multiple polygons

let ary = [
	{
    
    
		color:'red',//线条颜色 默认黑色
		size:1,//线条粗细 默认 1
		background:'',//填充颜色 默认透明
		data:[{
    
    x:100,y:173},{
    
    x:280,y:163},{
    
    x:280,y:380},{
    
    x:150,y:380}] //多边形点集合
	},
	{
    
    
		color:'green',
		size:1,
		background:'',
		data:[{
    
    x:200,y:173},{
    
    x:380,y:163},{
    
    x:380,y:380},{
    
    x:250,y:380}]
	},
	{
    
    
		color:'blue',
		size:1,
		background:'',
		data:[{
    
    x:230,y:373},{
    
    x:480,y:363},{
    
    x:280,y:180},{
    
    x:350,y:180},{
    
    x:200,y:400}]
	}
]
initCanvas('video','my-canvas',ary)

draw polygon method

/**
 * 
 * @param c canvas对象
 * @param arr 多边形各个坐标
 * @param color 线条颜色
 * @param size 线条粗细
 * @param background 背景色
 */
 function drawLine(c,arr,color,size,background){
    
    
	c.beginPath()
	arr.forEach(t=>{
    
    
		c.lineTo(t.x,t.y)
	})
	c.closePath()
	c.fillStyle = background||"transparent";
	c.strokeStyle = color||'#000';
	c.lineWidth = size||1;
	c.fill();
	c.stroke();
}

draw multiple polygons

/**
 * 加载划线
 * @param eleId 需要画多边形的div id
 * @param drawId 画布ID 自定义
 * @param arr  多边形数据集合
 */
function initCanvas(eleId,drawId,arr){
    
    
	var demo = document.getElementById(eleId)	
	let d_h = demo.offsetHeight   
	let d_w = demo.offsetWidth
	let rat_h = d_h/1080
	let rat_w = d_w/1920
	arr.forEach(t=>{
    
    
		t.data.forEach(d=>{
    
    
			d.x *= rat_w
			d.y *= rat_h
		})
	})
	let ele = document.getElementById(drawId)
	if(!ele){
    
    
		ele = document.createElement('canvas')
		ele.id = drawId
		ele.style.width = d_w + 'px'
		ele.style.height = d_h + 'px'
		ele.style.position = 'absolute'
		ele.style.background = 'none'
		ele.style.zIndex = '999'
		ele.style.top = '0px'
		demo.parentNode.appendChild(ele)
	}
	var c = document.getElementById(drawId).getContext("2d");
	c.clearRect(0,0,d_w,d_h)
	arr.forEach(t=>{
    
    
		drawLine(c,t.data,t.color,t.size,t.background)
	})  
}

Guess you like

Origin blog.csdn.net/yuanbo_520/article/details/129663799