canvas元素
letcanvasDOM =document.getElementById('box');letcav = canvasDOM.getContext('2d');复制代码
绘制线段
// 线段,两点一线// 设置起点cav.moveTo(150,100);// 设置终点cav.lineTo(300,100);// 设置线段颜色cav.strokeStyle ='skyblue';// 设置线段宽度cav.lineWidth ='8'// 绘制线段cav.stroke()复制代码
通过stroke方法构建画板
canvasDOM.onmousedown =function(event){letevent = e ||window.eventvarx = event.clientX -this.offsetLeft -parseInt(this.style.borderLeftWidth)vary = event.clientY -this.offsetTop -parseInt(this.style.borderTopWidth) cav.moveTo(x, y); canvasDOM.onmousemove =function(event){varx2 = event.clientX -this.offsetLeft -parseInt(this.style.borderLeftWidth)vary2 = event.clientY -this.offsetTop -parseInt(this.style.borderTopWidth) cavs.lineTo(x2, y2) cav.stroke() } canvasDOM.onmouseup =function(event){ canvasDOM.onmousemove =null}}复制代码
绘制路径
cav.beginPath();cav.moveTo(200,100);cav.lineTo(200,200);cav.lineTo(300,200);cav.closePath();cav.strokeStyle ='skyblue';cav.lineWidth ='5';cav.fillStyle ='pink';cav.fill()cav.stroke()复制代码
绘制矩形
cav.fillStyle ='skyblue'// 绘制填充矩形// fillRect(x,y,width,height)cav.fillRect(100,100,300,200)cav.strokeStyle ='pink'cav.lineWidth =8// 绘制矩形边框cav.strokeRect(100,100,300,200)// clearRect 在给定的矩形内清除指定的像素cav.clearRect(125,125,100,100)