这里推荐一个好用的在线编译器 https://jsbin.com/?html,js,output
html : 推荐样式写行内样式
<canvas id="mycanvas" width="300" height="300" style="border:1px solid black"></canvas>
js: 对canvas的操作都写在js中
var c = document.querySelector("#mycanvas")
var mycanvas = c.getContext(“2d”) // 得到一个二维的画布
- 矩形
//填充
mycanvas.fillStyle = "blue" // 填充样式为颜色
mycanvas.fillRect(0,0,50,50) // 填充区域是canvas标签的(x起点,y起点,x结束点,y结束点)
//描绘
mycanvas.strokeStyle = "red"
mycanvas.strokeRect(10,10,100,100)
- 描绘线条
mycanvas.moveTo(0,0) // 线条的起点(x起点,y起点)
mycanvas.lineTo(50,60) // 线条的终点(x终点,y终点)
mycanvas.lineWidth=10 // 线条的宽度 默认是1
mycanvas.strokeStyle="red" //线条样式写在描绘之前 strokeStyle为渐变对象,则为渐变的线条
mycanvas.stroke() //将线条描述出来 默认是黑色
- 画圆
mycanvas.beginPath() // 开始一条路径
mycanvas.arc(40,40,30,0,Math.PI*2) // 画一条弧线,(圆心x,圆心y,半径,0,Math.PI*2)
mycanvas.closePath() //将该路径连接到起始路径
mycanvas.strokeStyle="orange" //边框线条颜色
mycanvas.stroke()
mycanvas.fillStyle="red" //填充颜色
mycanvas.fill()
- 线性渐变
var gra = mycanvas.createLinearGradient(0,0,100,0) //左右方向,(0,0,0,100)上下方向
gra.addColorStop(0,"red")
gra.addColorStop(0.6,"skyblue")
gra.addColorStop(1,"green")
mycanvas.fillstyle = gra // 画布填充样式为渐变对象
mycanvas.fillRect(0,0,100,200) //填充区域
- 径向渐变
var gra=mycanvas.createRadialGradient(55,50,5,90,60,100);//渐变开始圆的x,开始圆的y,开始圆的半径,结束圆的x,结束圆的y,结束圆的半径
gra.addColorStop(0,"red")
gra.addColorStop(0.5,"pink")
gra.addColorStop(1,"blue")
mycanvas.fillStyle = gra
mycanvas.fillRect(0,0,300,300)
- 描边/实心文字 渐变样式
var gra = mycanvas.createLinearGradient(0,0,100,0)
gra.addColorStop(0,"red")
gra.addColorStop(1,"blue")
mycanvas.fillStyle = gra
mycanvas.strokeStyle = gra
mycanvas.font ="20px 微软雅黑"
mycanvas.strokeText("这是描边的文字",20,30)
mycanvas.fillText("这是实心的文字",20,80)
- 图片
<img src="http://img5.imgtn.bdimg.com/it/u=3300305952,1328708913&fm=26&gp=0.jpg">
var img = document.querySelector("img")
mycanvas.drawImage(img,10,10)
- 重复指定的元素
<img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1561574086181&di=7a3fd86240659b9bc2d720c8bafb34d9&imgtype=0&src=http%3A%2F%2Fg.hiphotos.baidu.com%2Fnuomi%2FeWH%3D216%2C140%2Fsign%3D6b72786c7bf082023ff8ec3279cacdc1%2F77094b36acaf2edd65f5d5a6851001e93901937d.jpg">
var img = document.querySelector("img")
var par = mycanvas.createPattern(img,"repeat") // repeat, repeat-x,repeat-y
mycanvas.fillStyle = par
mycanvas.fillRect(0,0,300,300)