canvas用途
- 游戲 小游戲
- 圖表 報(bào)表 如 Charts插件
- 炫酷效果 banner
- 模擬器、圖形編輯器 等
兼容性
IE9以上和其他瀏覽器
canvas 標(biāo)簽
屬性
- width
- height
方法
- getContext() 參數(shù) 2d/webgl
注意
css設(shè)置的寬高跟width/height設(shè)置的寬高 不同
Context環(huán)境
通過(guò) getContext方法獲取繪圖環(huán)境(繪圖上下文)(對(duì)象)
繪制圖形通過(guò)該對(duì)象提供的方法/屬性
基本繪圖
路徑
- moveTo() 起始位置
- lineTo() 直線 摧冀,如果沒(méi)有moveTo() 第一個(gè)lineTo()替代 moveTo()
路徑的開(kāi)始和關(guān)閉
- beginPath() 開(kāi)啟路徑
- closePath() 關(guān)閉路徑 結(jié)束當(dāng)前的路徑塘砸,自動(dòng)閉合
- 注意: 復(fù)雜的圖形游桩,一定要開(kāi)啟和關(guān)閉路徑
描邊 stroke()
- stroke() 方法
- strokeStyle 設(shè)置描邊顏色
- lineWidth 設(shè)置描邊的粗細(xì)
填充
- fill() 填充
- fillStyle 設(shè)置填充顏色
快速矩形工具
- rect(x, y, width, height) 繪制矩形路徑
- strokeRect(x, y, width, height) 描邊矩形
- fillRect(x,y,width,height) 填充矩形
- clearRect(x,y,w,h) 清除矩形 (矩形范圍內(nèi)的內(nèi)容會(huì)被擦除)
圓形(圓弧)
- arc(x,y,r,start, end, wise) 繪制圓弧
- start/end是起始位置 單位是 弧度 色迂, 360角度 = 2PI蚀狰, 180角度 = PI
- 最后一個(gè)參數(shù) 順時(shí)針(false)/逆時(shí)針(true) 默認(rèn)false
內(nèi)容
文字方法
- strokeText(text, x, y) 描邊寫(xiě)字
- fillText(text, x, y) 填充寫(xiě)字
- measureText(text) 返回對(duì)象 包換文本的寬度
- font 屬性 設(shè)置 大小、字體 如
cxt.fon="100px MicrosoftYaHei"
; - textAlign 屬性 水平對(duì)齊方式 start(默認(rèn))/end/center/left/right
- textBaseline 屬性 垂直對(duì)齊方式 alphabetic(默認(rèn))/top/bottom/middke/hanging/ideographic
繪制圖片(插入圖片)
插入圖片
drawImage(img, x, y)
- img image的dom元素
- x,y 插入到 畫(huà)布的位置 坐標(biāo)
插入圖片并改變大小
drawImage(img, x, y, width, height)
插入裁剪后的圖片
drawImage(img, sx,sy,swidth,sheight, x, y, width, height)
- sx/sy: 圖片上開(kāi)始裁剪的位置
- swidth/sheight : 裁剪圖片的大小
陰影
- shadowColor 陰影顏色
- shadowBlur 陰影的模糊值
- shadowOffsetX 陰影的左偏移量
- shadowOffsetY 陰影的右偏移量
漸變
線性漸變
var grd = cxt.createLinearGradien(x, y, x1, y1);
//參數(shù):x,y起始坐標(biāo),x1,y1結(jié)束坐標(biāo)
例如:
//創(chuàng)建線性漸變的對(duì)象,
var grd=ctx.createLinearGradient(0,0,170,0);
grd.addColorStop(0,"black"); //添加一個(gè)漸變顏色朽色,第一個(gè)參數(shù)介于 0.0 與 1.0 之間的值栖榨,表示漸變中開(kāi)始與結(jié)束之間的位置。
grd.addColorStop(1,"white"); //添加一個(gè)漸變顏色
ctx.fillStyle =grd; //關(guān)鍵點(diǎn)垒在,把漸變?cè)O(shè)置到 填充的樣式
徑向漸變
- createRadiaGradient(x1, y1, r1, x2, y2, r2)
- addColorStop()
把背景圖片作為填充
- createPattern(imgDom, repeate)
- 第二個(gè)參數(shù) repeate/ repeat-x / repeat-y / no-repeat
變換
縮放
- sacle(x, y)
位移
- translate(x, y)
旋轉(zhuǎn)
- rotate(angle)
環(huán)境的保存和恢復(fù)
- save()
- restore()
設(shè)置透明
- globalAlpha = number 設(shè)置不透明度
- 全局設(shè)置是對(duì)整個(gè)畫(huà)布(繪圖環(huán)境) 進(jìn)行設(shè)置
限定繪圖區(qū)域
- clip()
輸出base64編碼
- canvas.toDataURL(type, encoder)
- type為mime類(lèi)型 image/jpeg image/gif image/png image/webp
畫(huà)布渲染畫(huà)布
把一個(gè)畫(huà)布以圖片的形式用 drawImage() 插入到另一個(gè)畫(huà)布
這是一種canvas的優(yōu)化手段
設(shè)置線條
- lineCap 屬性 設(shè)置線條兩端的形狀 butt/round/square
- lineJoin 屬性 設(shè)置線條夾角 miter/bevel/round
- miterLimit 屬性 設(shè)置夾角斜角的最大長(zhǎng)度 一般默認(rèn) 10