Canvas API(畫布)用於在網頁實時生成圖像,而且能夠操做圖像內容,基本上它是一個能夠用JavaScript操做的位圖(bitmap)。javascript
<canvas>
網頁元素。<canvas id="myCanvas" width="400" height="200">
你的瀏覽器不支持canvas!
</canvas>
複製代碼
上面代碼中,若是瀏覽器不支持這個API,則就會顯示<canvas>
標籤中間的文字——「您de瀏覽器不支持canvas!」。html
var canvas = document.getElementById('myCanvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
}
複製代碼
上面代碼中,getContext
方法指定參數2d
,表示該canvas
節點用於生成2D圖案(即平面圖案)。若是參數是webgl
,就表示用於生成3D圖像(即立體圖案),這部分實際上單獨叫作WebGL API。vue
canvas
畫布提供了一個用來做圖的平面空間,該空間的每一個點都有本身的座標,x表示橫座標,y表示豎座標。原點(0, 0)位於圖像左上角,x軸的正向是原點向右,y軸的正向是原點向下java
beginPath
方法表示開始繪製路徑,moveTo(x, y)
方法設置線段的起點,lineTo(x, y)
方法設置線段的終點,stroke
方法用來給透明的線段着色。web
ctx.beginPath(); // 開始路徑繪製
ctx.moveTo(20, 20); // 設置路徑起點,座標爲(20,20)
ctx.lineTo(200, 20); // 繪製一條到(200,20)的直線
ctx.lineWidth = 1.0; // 設置線寬
ctx.strokeStyle = '#CC0000'; // 設置線的顏色
ctx.stroke(); // 進行線的着色,這時整條線才變得可見
複製代碼
moveto和lineto方法能夠屢次使用。最後,還能夠使用closePath方法,自動繪製一條當前點到起點的直線,造成一個封閉圖形,省卻使用一次lineto方法。算法
fillRect(x, y, width, height)
方法用來繪製矩形,它的四個參數分別爲矩形左上角頂點的x座標、y座標,以及矩形的寬和高。fillStyle屬性用來設置矩形的填充色。canvas
ctx.fillStyle = 'yellow';
ctx.fillRect(50, 50, 200, 100);
複製代碼
strokeRect方法與fillRect相似,用來繪製空心矩形。數組
ctx.strokeRect(10,10,200,100);
複製代碼
clearRect方法用來清除某個矩形區域的內容。瀏覽器
ctx.clearRect(100,50,50,50);
複製代碼
fillText(string, x, y)
用來繪製文本,它的三個參數分別爲文本內容、起點的x座標、y座標。使用以前,需用font設置字體、大小、樣式(寫法相似與CSS的font屬性)。與此相似的還有strokeText
方法,用來添加空心字。app
// 設置字體
ctx.font = "Bold 20px Arial";
// 設置對齊方式
ctx.textAlign = "left";
// 設置填充顏色
ctx.fillStyle = "#008600";
// 設置字體內容,以及在畫布上的位置
ctx.fillText("Hello!", 10, 50);
// 繪製空心字
ctx.strokeText("Hello!", 10, 100);
複製代碼
fillText方法不支持文本斷行,即全部文本出如今一行內。因此,若是要生成多行文本,只有調用屢次fillText方法。
arc
方法用來繪製扇形
ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
複製代碼
arc方法的x和y參數是圓心座標,radius是半徑,startAngle和endAngle則是扇形的起始角度和終止角度(以弧度表示),anticlockwise表示作圖時應該逆時針畫(true)仍是順時針畫(false)。
下面是如何繪製實心的圓形。
ctx.beginPath();
ctx.arc(60, 60, 50, 0, Math.PI*2, true);
ctx.fillStyle = "#000000";
ctx.fill();
複製代碼
繪製空心圓形的例子。
ctx.beginPath();
ctx.arc(60, 60, 50, 0, Math.PI*2, true);
ctx.lineWidth = 1.0;
ctx.strokeStyle = "#000";
ctx.stroke();
複製代碼
createLinearGradient方法用來設置漸變色。
var myGradient = ctx.createLinearGradient(0, 0, 0, 160);
myGradient.addColorStop(0, "#BABABA");
myGradient.addColorStop(1, "#636363");
複製代碼
createLinearGradient方法的參數是(x1, y1, x2, y2),其中x1和y1是起點座標,x2和y2是終點座標。經過不一樣的座標值,能夠生成從上至下、從左到右的漸變等等。
使用方法以下:
ctx.fillStyle = myGradient;
ctx.fillRect(10,10,200,100);
複製代碼
一系列與陰影相關的方法,能夠用來設置陰影。
ctx.shadowOffsetX = 10; // 設置水平位移
ctx.shadowOffsetY = 10; // 設置垂直位移
ctx.shadowBlur = 5; // 設置模糊度
ctx.shadowColor = "rgba(0,0,0,0.5)"; // 設置陰影顏色
ctx.fillStyle = "#CC0000";
ctx.fillRect(10,10,200,100);
複製代碼
Canvas API 容許將圖像文件插入畫布,作法是讀取圖片後,使用
drawImage
方法在畫布內進行重繪。
var img = new Image();
img.src = 'image.png';
ctx.drawImage(img, 0, 0); // 設置對應的圖像對象,以及它在畫布上的位置
複製代碼
上面代碼將一個PNG圖像載入畫布。drawImage()方法接受三個參數,第一個參數是圖像文件的DOM元素(即<img>
節點),第二個和第三個參數是圖像左上角在畫布中的座標,上例中的(0, 0)就表示將圖像左上角放置在畫布的左上角。
因爲圖像的載入須要時間,drawImage方法只能在圖像徹底載入後才能調用,所以上面的代碼須要改寫。
var image = new Image();
image.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext('2d').drawImage(image, 0, 0);
// 插入頁面底部
document.body.appendChild(image);
return canvas;
}
image.src = 'image.png';
複製代碼
getImageData方法能夠用來讀取Canvas的內容,返回一個對象,包含了每一個像素的信息。
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
複製代碼
imageData對象有一個data屬性,它的值是一個一維數組。該數組的值,依次是每一個像素的紅、綠、藍、alpha通道值,所以該數組的長度等於 圖像的像素寬度 x 圖像的像素高度 x 4,每一個值的範圍是0–255。這個數組不只可讀,並且可寫,所以經過操做這個數組的值,就能夠達到操做圖像的目的。修改這個數組之後,使用putImageData
方法將數組內容從新繪製在Canvas上。
context.putImageData(imageData, 0, 0);
複製代碼
對圖像數據作出修改之後,能夠使用
toDataURL
方法,將Canvas數據從新轉化成通常的圖像文件形式。
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL('image/png');
return image;
}
複製代碼
上面的代碼將Canvas數據,轉化成PNG data URI。
save方法用於保存上下文環境,restore方法用於恢復到上一次保存的上下文環境。
ctx.save();
ctx.shadowOffsetX = 10;
ctx.shadowOffsetY = 10;
ctx.shadowBlur = 5;
ctx.shadowColor = 'rgba(0,0,0,0.5)';
ctx.fillStyle = '#CC0000';
ctx.fillRect(10,10,150,100);
ctx.restore();
ctx.fillStyle = '#000000';
ctx.fillRect(180,10,150,100);
複製代碼
上面代碼先用save方法,保存了當前設置,而後繪製了一個有陰影的矩形。接着,使用restore方法,恢復了保存前的設置,繪製了一個沒有陰影的矩形。
利用JavaScript,能夠在canvas元素上很容易地產生動畫效果。
var posX = 20,
posY = 100;
setInterval(function() {
context.fillStyle = "black";
context.fillRect(0,0,canvas.width, canvas.height);
posX += 1;
posY += 0.25;
context.beginPath();
context.fillStyle = "white";
context.arc(posX, posY, 10, 0, Math.PI*2, true);
context.closePath();
context.fill();
}, 30);
複製代碼
上面代碼會產生一個小圓點,每隔30毫秒就向右下方移動的效果。setInterval函數的一開始,之因此要將畫布從新渲染黑色底色,是爲了抹去上一步的小圓點。
經過設置圓心座標,能夠產生各類運動軌跡。
先上升後降低。
var vx = 10,
vy = -10,
gravity = 1;
setInterval(function() {
posX += vx;
posY += vy;
vy += gravity;
// ...
});
複製代碼
上面代碼中,x座標始終增大,表示持續向右運動。y座標先變小,而後在重力做用下,不斷增大,表示先上升後降低。
小球不斷反彈後,逐步趨於靜止。
var vx = 10,
vy = -10,
gravity = 1;
setInterval(function() {
posX += vx;
posY += vy;
if (posY > canvas.height * 0.75) {
vy *= -0.6;
vx *= 0.75;
posY = canvas.height * 0.75;
}
vy += gravity;
// ...
});
複製代碼
上面代碼表示,一旦小球的y座標處於屏幕下方75%的位置,向x軸移動的速度變爲原來的75%,而向y軸反彈上一次反彈高度的40%。
經過getImageData方法和putImageData方法,能夠處理每一個像素,進而操做圖像內容。
假定filter是一個處理像素的函數,那麼整個對Canvas的處理流程,能夠用下面的代碼表示。
if (canvas.width > 0 && canvas.height > 0) {
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
filter(imageData);
context.putImageData(imageData, 0, 0);
}
複製代碼
如下是幾種常見的處理方法。
灰度圖(grayscale)就是取紅、綠、藍三個像素值的算術平均值,這實際上將圖像轉成了黑白形式。假定d[i]是像素數組中一個象素的紅色值,則d[i+1]爲綠色值,d[i+2]爲藍色值,d[i+3]就是alpha通道值。轉成灰度的算法,就是將紅、綠、藍三個值相加後除以3,再將結果寫回數組。
grayscale = function (pixels) {
var d = pixels.data;
for (var i = 0; i < d.length; i += 4) {
var r = d[i];
var g = d[i + 1];
var b = d[i + 2];
d[i] = d[i + 1] = d[i + 2] = (r+g+b)/3;
}
return pixels;
};
複製代碼
復古效果(sepia)則是將紅、綠、藍三個像素,分別取這三個值的某種加權平均值,使得圖像有一種古舊的效果。
sepia = function (pixels) {
var d = pixels.data;
for (var i = 0; i < d.length; i += 4) {
var r = d[i];
var g = d[i + 1];
var b = d[i + 2];
d[i] = (r * 0.393)+(g * 0.769)+(b * 0.189); // red
d[i + 1] = (r * 0.349)+(g * 0.686)+(b * 0.168); // green
d[i + 2] = (r * 0.272)+(g * 0.534)+(b * 0.131); // blue
}
return pixels;
};
複製代碼
紅色蒙版指的是,讓圖像呈現一種偏紅的效果。算法是將紅色通道設爲紅、綠、藍三個值的平均值,而將綠色通道和藍色通道都設爲0。
red = function (pixels) {
var d = pixels.data;
for (var i = 0; i < d.length; i += 4) {
var r = d[i];
var g = d[i + 1];
var b = d[i + 2];
d[i] = (r+g+b)/3; // 紅色通道取平均值
d[i + 1] = d[i + 2] = 0; // 綠色通道和藍色通道都設爲0
}
return pixels;
};
複製代碼
亮度效果(brightness)是指讓圖像變得更亮或更暗。算法將紅色通道、綠色通道、藍色通道,同時加上一個正值或負值。
brightness = function (pixels, delta) {
var d = pixels.data;
for (var i = 0; i < d.length; i += 4) {
d[i] += delta; // red
d[i + 1] += delta; // green
d[i + 2] += delta; // blue
}
return pixels;
};
複製代碼
反轉效果(invert)是指圖片呈現一種色彩顛倒的效果。算法爲紅、綠、藍通道都取各自的相反值(255-原值)。
invert = function (pixels) {
var d = pixels.data;
for (var i = 0; i < d.length; i += 4) {
d[i] = 255 - d[i];
d[i+1] = 255 - d[i + 1];
d[i+2] = 255 - d[i + 2];
}
return pixels;
};
複製代碼
vue 動畫小組件
<template>
<canvas ref="bubble" :width="width" :height="height" :style="style"></canvas>
</template>
<script type="text/ecmascript-6"> export default { props: { y: { type: Number, default: 0 } }, data() { return { width: 50, height: 80 } }, computed: { distance() { return Math.max(0, Math.min(this.y * this.ratio, this.maxDistance)) }, style() { return `width:${this.width / this.ratio}px;height:${this.height / this.ratio}px` } }, created() { this.ratio = window.devicePixelRatio this.width *= this.ratio this.height *= this.ratio this.initRadius = 18 * this.ratio this.minHeadRadius = 12 * this.ratio this.minTailRadius = 5 * this.ratio this.initArrowRadius = 10 * this.ratio this.minArrowRadius = 6 * this.ratio this.arrowWidth = 3 * this.ratio this.maxDistance = 40 * this.ratio this.initCenterX = 25 * this.ratio this.initCenterY = 25 * this.ratio this.headCenter = { x: this.initCenterX, y: this.initCenterY } }, mounted() { this._draw() }, methods: { _draw() { const bubble = this.$refs.bubble let ctx = bubble.getContext('2d') ctx.clearRect(0, 0, bubble.width, bubble.height) this._drawBubble(ctx) this._drawArrow(ctx) }, _drawBubble(ctx) { ctx.save() ctx.beginPath() const rate = this.distance / this.maxDistance const headRadius = this.initRadius - (this.initRadius - this.minHeadRadius) * rate this.headCenter.y = this.initCenterY - (this.initRadius - this.minHeadRadius) * rate // 畫上半弧線 ctx.arc(this.headCenter.x, this.headCenter.y, headRadius, 0, Math.PI, true) // 畫左側貝塞爾 const tailRadius = this.initRadius - (this.initRadius - this.minTailRadius) * rate const tailCenter = { x: this.headCenter.x, y: this.headCenter.y + this.distance } const tailPointL = { x: tailCenter.x - tailRadius, y: tailCenter.y } const controlPointL = { x: tailPointL.x, y: tailPointL.y - this.distance / 2 } ctx.quadraticCurveTo(controlPointL.x, controlPointL.y, tailPointL.x, tailPointL.y) // 畫下半弧線 ctx.arc(tailCenter.x, tailCenter.y, tailRadius, Math.PI, 0, true) // 畫右側貝塞爾 const headPointR = { x: this.headCenter.x + headRadius, y: this.headCenter.y } const controlPointR = { x: tailCenter.x + tailRadius, y: headPointR.y + this.distance / 2 } ctx.quadraticCurveTo(controlPointR.x, controlPointR.y, headPointR.x, headPointR.y) ctx.fillStyle = 'rgb(170,170,170)' ctx.fill() ctx.strokeStyle = 'rgb(153,153,153)' ctx.stroke() ctx.restore() }, _drawArrow(ctx) { ctx.save() ctx.beginPath() const rate = this.distance / this.maxDistance const arrowRadius = this.initArrowRadius - (this.initArrowRadius - this.minArrowRadius) * rate // 畫內圓 ctx.arc(this.headCenter.x, this.headCenter.y, arrowRadius - (this.arrowWidth - rate), -Math.PI / 2, 0, true) // 畫外圓 ctx.arc(this.headCenter.x, this.headCenter.y, arrowRadius, 0, Math.PI * 3 / 2, false) ctx.lineTo(this.headCenter.x, this.headCenter.y - arrowRadius - this.arrowWidth / 2 + rate) ctx.lineTo(this.headCenter.x + this.arrowWidth * 2 - rate * 2, this.headCenter.y - arrowRadius + this.arrowWidth / 2) ctx.lineTo(this.headCenter.x, this.headCenter.y - arrowRadius + this.arrowWidth * 3 / 2 - rate) ctx.fillStyle = 'rgb(255,255,255)' ctx.fill() ctx.strokeStyle = 'rgb(170,170,170)' ctx.stroke() ctx.restore() } }, watch: { y() { this._draw() } } } </script>
<style scoped> </style>
複製代碼