Canvas作為前端的畫圖工具,其實用途還是蠻廣泛的,但是很多前端學習課程其實都很少涉及到這塊內容。
于是乎,就寫下這個了。
當然啦,目前還在學習摸索中。
一些實戰代碼,僅供參考:
<canvasid="ctx"width="300px"height="300px"style="border: 1px solid;margin: 100px 0 0 666px;"><!-- border不起效果,不能直接使用border,而是用style去寫,個人不建議使用這個border。默認寬高是300*150px--></canvas><script>// 通過id去獲取canvas,這里不需要#const myCtx = document.getElementById('ctx')// 通過getContext()方法創建2d平面const ctx = myCtx.getContext("2d")// --------------------------------------------// 要求:畫一個矩形// ctx.rect(100, 100, 100, 100)// 前面兩個是起始的坐標位置,后面兩個是寬高// 改變筆頭// ctx.strokeStyle = "red"// 設置畫筆的像素值// ctx.lineWidth = 3// 使用stroke()是畫出形狀,不會填充// ctx.stroke()// 使用fill是填充的意思// ctx.fill()// --------------------------------------------// 使用簡單方法畫矩形// 改變筆頭// ctx.strokeStyle = "red"// 使用strokeRect()畫出// ctx.strokeRect(125, 125, 50, 50)// 使用fillStyle,改變畫筆顏色// ctx.fillStyle = "red"// 使用fillRect()填充// ctx.fillRect(100, 100, 100, 100)// 使用clearRect()清空// ctx.clearRect(125, 125, 50, 50)// -------------------------------------// 畫一個三角形// 移動筆尖// ctx.moveTo(30, 40)// 先畫出一條橫線// ctx.lineTo(270, 40)// 再畫出一條豎線// ctx.lineTo(270, 260)// 回到起點,閉合整個曲線// ctx.closePath()// -------------------------------------// 畫一個圓形// 最后結束角不能是0,圓形必須是2*Math.PI// 還有個參數的——關于畫的方向的,但是默認是順時針,這里使用默認效果。// 從X軸開始出發,X軸算是0°// ctx.arc(150, 150, 50, 0, 2 * Math.PI)// 改變顏色// ctx.strokeStyle = "blue"// 完成繪圖// ctx.stroke()// 改變填充顏色// ctx.fillStyle = "red"// 完成繪圖// ctx.fill()// -------------------------------------// 畫一個橢圓 - 不閉合的ctx.arc(150, 150, 88, 0, 1.8*Math.PI)// 改變畫筆顏色// ctx.strokeStyle = "orange"// 完成繪圖// ctx.stroke()// 改變填充顏色// ctx.fillStyle = "green"// 完成繪圖 - 有bug - 并不是橢圓,而是被切了一小塊的圓// ctx.fill()// 完善 - 閉合圖案// 筆尖回到圓點// ctx.lineTo(150, 150)// 兩段閉合// ctx.closePath()// 填充// ctx.fill()// -----------------------------------// 畫一個圓ctx.arc(150, 150, 100, 0, 1.6 * Math.PI)// 要求:漸變色的橢圓形// 設置線性漸變色// const gradient = ctx.createLinearGradient(200, 200, 50, 50)// 設置放射狀漸變色 - 在起始和結尾坐標處添加了半徑const gradient = ctx.createRadialGradient(180, 180, 100, 75, 75, 100)// 添加顏色 - 注意前面的數字和后面的顏色gradient.addColorStop(0, "black")gradient.addColorStop("0.5", "#999")gradient.addColorStop("0.8", "red")gradient.addColorStop(1, "blue")// 直接填充ctx.fillStyle = gradient// 筆尖回到圓點ctx.lineTo(150, 150)// 兩段閉合ctx.closePath()// 完成繪圖ctx.fill()
注意最后一個橢圓的閉合的實現:
閉合前:
閉合后:
?
增加了漸變色的處理。
線性漸變和放射狀漸變方法差不多,只不過創建函數有所區別。
其中放射狀漸變需要注意的是,半徑最好跟圓的半徑一致,否則就會出現:
本節完。