<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属性来获取宽度。