填充
纯色
var cvs = document.getElementById("myCanvas");
var ctx = cvs.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,150,75);
渐变填充
径向渐变
var cvs = document.getElementById('myCanvasBgGradientColor')
var ctx = cvs.getContext("2d")
// 创建渐变1 - 45度径向渐变
var grd1 = ctx.createLinearGradient(0, 0, 100, 100);
grd1.addColorStop(0, 'red')
grd1.addColorStop(1, 'white')
// 创建渐变2 - 横向径向渐变
var grd2 = ctx.createLinearGradient(100, 100, 200, 100);
grd2.addColorStop(0, 'red')
grd2.addColorStop(1, 'white')
// 填充渐变1
ctx.fillStyle = grd1
ctx.fillRect(0, 0, 100, 100)
// 填充渐变2
ctx.fillStyle = grd2
ctx.fillRect(100, 100, 200, 200)
球型/放射渐变
var cvs = document.getElementById('myCanvasBgRadialGradientColor')
var ctx = cvs.getContext("2d")
// 创建渐变
var grd = ctx.createRadialGradient(100, 100, 0, 100, 100, 90);
grd.addColorStop(0, 'red')
grd.addColorStop(1, 'green')
// 填充渐变
ctx.fillStyle = grd
ctx.fillRect(0, 0, 200, 200)
图片填充
var cvs = document.getElementById('myCanvas')
var ctx = cvs.getContext("2d")
var img = new Image()
img.src = 'https://visualhunt.com/photos/1/milky-way-over-fence.jpg?s=l'
img.onload = function () {
var pattern = ctx.createPattern(img, "no-repeat")
ctx.fillStyle = pattern
ctx.fillRect(10, 10, 780, 510) // 图片尺寸800x530
}
图形
直线
var cvs = document.getElementById('myCanvasLine')
var ctx = cvs.getContext("2d")
ctx.moveTo(10, 10)
ctx.lineTo(120, 150)
ctx.strokeStyle = '#FF0000'
ctx.stroke()
圆形
var cvs = document.getElementById('myCanvasCircle')
var ctx = cvs.getContext("2d")
ctx.beginPath()
ctx.arc(100, 100, 30, 0, 2 * Math.PI)
ctx.strokeStyle = '#FF0000'
ctx.stroke()
圆弧
var cvs = document.getElementById('myCanvasCircle')
var ctx = cvs.getContext("2d")
ctx.beginPath()
ctx.arc(100, 100, 30, 0, 0.5 * Math.PI)
ctx.strokeStyle = '#FF0000'
ctx.stroke()