<!--畫布寬高在屬性中設置-->
<canvas id="canvas" width="500" height="400"></canvas>
複製代碼
// 獲取畫布
const canvas = document.getElementById('canvas')
// 獲取2d畫筆
const cox = canvas.context('2d')
複製代碼
// 清空畫布
convas.clearRect(x,y,w,h)
複製代碼
// 設置起始點
cox.moveTo(x,y)
// 繪製線條
cox.lineTo(x,y)
// 描邊
cox.strake()
// 填充
cox.fill()
//閉合路徑
cox.closePath()
//新建路徑
cox.beginPath()
複製代碼
// 繪製矩形
cox.rect(x,y,w,h)
// 繪製並描邊
cox.strakeRect(x,y,w,h)
// 繪製並填充
cox.fillRect(x,y,w,h)
複製代碼
lineStyle 線條寬度,默認1px
strokeStyle 描邊樣式,只支持color
fillStyle 填充樣式,只支持
lineCap 線條末端樣式(默認butt) round(圓角) square(方形)
lineJoin 線條相交樣式(morenmiter) round(圓角) bevel(平角)
複製代碼
// 繪製填充文字
// 參數1: 繪製的文字
// 參數2: 位置
// 參數3: 最大寬度,文字寬度大於最大寬度時文字會被壓縮
fillText(text,x,y,[maxwidth])
複製代碼
// 繪製爲未填充文字
strokeText(text,x,y,[maxwidth])
// 獲取文字對象
measureText() obj.width可獲取寬度
複製代碼
// img:圖片對象
// x,y表明圖片左上角座標
// w,h圖標繪製尺寸的大小,會縮放圖片
// 須要等待圖片加載成功後在調用該方法
var img = mew Image();
img.src = '路徑'
img.onload=function (){
drawImage(img,x,y,w,h)
}
複製代碼
// x,y,w,h 表示圖片的左上角位置座標和大小
// x1,y1,w1,h1 表示畫布顯示區域的中心點座標和大小
drawImage(img,x,y,w,h,x1,y1,w1,h)
複製代碼
requestAnimationFrame()
相似於setTimeOut,須要在遞歸函數中實現canvas
function frame (){
console.log('動畫')
requestAnimationFrame(frame)
}
frame()
複製代碼