填充
純色
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()