<canvas>標籤
有屬性width/height可以用來設置寬高,
但是寬高默認爲:300px * 150px (width * height)
javascript操縱:
getContext( "2d" ):獲取CanvasRenderingContext2D對象。
校驗兼容性:
var canvas = document.getElementById('tutorial'); if (canvas.getContext){ var ctx = canvas.getContext('2d'); // drawing code here } else { // canvas-unsupported code here }
簡單的操作:
繪製矩形:
fillRect(x, y, width, height)
strokeRect(x, y, width, height)
clearRect(x, y, width, height)
rect(x, y, width, height)
//當調用該方法,moveTo()的自動調用,參數爲(0,0)
路徑:
beginPath()
closePath()
fill() //可以填充沒有閉合的圖形
stroke()
繪製圓形:
arc(x, y, radius, startAngle, endAngle, anticlockwise)
繪製Bezier and quadratic曲線:
quadraticCurveTo(cp1x, cp1y, x, y)
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
操縱圖像:
首先創建圖像對象:
var img = new Image(); // Create new img element
img.src = '1.png'; // Set source path
或者引用圖像對象
然後使用
drawImage(image, x, y)
drawImage(image, x, y, width, height)
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
注意:要在圖片加載完後使用:
var img = new Image(); // Create new img element
img.addEventListener("load", function() {
// execute drawImage statements here
}, false);
img.src = 'myImage.png'; // Set source path
使用style和color
fillStyle = color/gradient object/pattern object
strokeStyle = color/gradient object/pattern object
默認情況下:color爲:black
透明度:
globalAlpha:設置當前的透明度
rgba(255,0,0,0.5):使用rgba來設置透明度,最後一個參數(0-1)
style:
lineWidth = value //值必須是正數,默認值爲1
lineCap = type //but , round , square
lineJoin = type //miter , round , bevel
miterLimit = value
gradient:
createLinearGradient(beginX, beginY, endX, endY)
createRadialGradient(beginX, beginY, r1, endX, endY, r2)
可以通過 addColorStop()爲漸變分配顏色
gradient.addColorStop(position, color)
pattern:
createPattern(image, type)
type:repeat,x-repeat,y-repeat,no-repeat
shadow:
shadowOffsetX = float
shadowOffsetY = float
shadowBlur = float
//上面3個屬性的值不會受變換矩陣的影響,默認爲0
shadowColor = <color>
座標變換:
save()
restore()
translate:translate(x, y)
rotating:rotate(angle)
scaling:scale(x, y)
transform:transform(m11, m12, m21, m22, dx, dy)
setTransform(m11, m12, m21, m22, dx, dy)
圖像組合:
composition:globalCompositeOperation = type
clip()
圖像動畫:
animation:
基本步驟:Clear the canvas
Save the canvas state
Draw animated shapes
Restore the canvas state
文字:
填充文字:fillText(string,x,y[,MaxWidth])
繪製輪廓:strokeText(string,x,y[,MaxWidth])
屬性:
font
textAlign
textBaseline
測量文字寬度:
獲取measureText對象,
使用width屬性來獲取寬度。