Canvas
canvas 最早由Apple引入WebKit,用於Mac OS X 的 Dashboard,後來又在Safari和Google Chrome被實現。
基於 Gecko 1.8的瀏覽器,比如 Firefox 1.5, 同樣支持這個元素。
<canvas> 元素是WhatWG Web applications 1.0規範的一部分,也包含於HTML 5中。canvas因爲是html5引入的, 存在兼容性問題
體驗Canvas
什麼是Canvas?
HTML5 的 canvas 元素使用 JavaScript 在網頁上繪製圖像。
畫布是一個矩形區域,您可以控制其每一像素。
canvas 擁有多種繪製路徑、矩形、圓形、字符以及添加圖像的方法。
創建Canvas元素
向 HTML5 頁面添加 canvas 元素。
規定元素的 id、寬度和高度:
/*屬性 width 和 height屬性指的是畫布的大小*/
<canvas id="myCanvas" width="200" height="100"></canvas>
注意:不要在css中設置canvas的寬高,css中設置的是canvas的大小,而不是canvas中畫布的大小
通過JavaScript來繪製
/*獲取元素*/
var myCanvas = document.querySelector('#myCanvas');
/*獲取繪圖工具*/
var context = myCanvas.getContext('2d');
/*設置繪圖的起始位置*/
context.moveTo(100,100);
/*繪製路徑*/
context.lineTo(200,100);
/*描邊*/
context.stroke();
/*設置繪圖的起始位置*/
context.moveTo(150.5,150.5);
/*繪製路徑*/
context.lineTo(250.5,150.5);
/*描邊*/
context.stroke();
# 關於canvas中的0.5
https://www.jianshu.com/p/c0970eecd843
Canvas的基本使用
圖形繪製
需要理解些概念:
-
路徑的概念
-
路徑的繪製
- 描邊 stroke()
- 填充 fill()
-
閉合路徑
- 手動閉合
- 程序閉合 closePath()
-
填充規則(非零環繞)
非零環繞的規則: 1.從需要判斷是否要填充的區域開始隨便拉一條線出去 2.看所有和拉出去的那條線相交的點,方向順時針+1,逆時針-1 3.看上面第二步+1 和 -1後的結果。如果結果是0,則不填充。如果結果不是0,則填充
- 開啓新的路徑 beginPath()
設置樣式
- 畫筆的狀態
- lineWidth 線寬,默認1px
- lineCap 線末端類型:(butt默認)、round、square
- lineJoin 相交線的拐點 miter(默認)、round、bevel
- strokeStyle 線的顏色
- fillStyle 填充顏色
- setLineDash() 設置虛線
- getLineDash() 獲取虛線寬度集合
- lineDashOffset 設置虛線偏移量(負值向右偏移)
案例:
繪製三條不同顏色的平行線
/*繪製三條不同顏色的平行線*/
<script>
var myCanvas = document.querySelector('canvas');
var ctx = myCanvas.getContext('2d');
/*畫平行線*/
ctx.beginPath();/*開啓新路徑*/
/*藍色 10px*/
ctx.moveTo(100,100);
ctx.lineTo(300,100);
ctx.strokeStyle = 'blue';
ctx.lineWidth = 10;
/*描邊*/
ctx.stroke();
/*紅色 20px*/
ctx.beginPath();/*開啓新路徑*/
ctx.moveTo(100,200);
ctx.lineTo(300,200);
ctx.strokeStyle = 'red';
ctx.lineWidth = 20;
/*描邊*/
ctx.stroke();
/*綠色 30px*/
ctx.beginPath();/*開啓新路徑*/
ctx.moveTo(100,300);
ctx.lineTo(300,300);
ctx.strokeStyle = 'green';
ctx.lineWidth = 30;
/*描邊*/
ctx.stroke();
</script>
繪製三角形(填充/描邊)
var myCanvas = document.querySelector('canvas');
var ctx = myCanvas.getContext('2d');
/*1.繪製一個三角形*/
ctx.moveTo(100,100);
ctx.lineTo(200,100);
ctx.lineTo(200,200);
/*起始點和lineTo的結束點無法完全閉合缺角*/
/*使用canvas的自動閉合 */
//ctx.lineTo(100,100);
/*關閉路徑*/
ctx.closePath();
ctx.lineWidth = 10;
/*2.描邊*/
ctx.stroke();
/*3.填充*/
//ctx.fill();
繪製鏤空正方形
var myCanvas = document.querySelector('canvas');
var ctx = myCanvas.getContext('2d');
/*1.繪製兩個正方形 一大200一小100 套在一起*/
ctx.moveTo(100,100);
ctx.lineTo(300,100);
ctx.lineTo(300,300);
ctx.lineTo(100,300);
ctx.closePath();
/*注意繪製圖形時候點的順序,順序的不同會產生非零環繞的問題*/
ctx.moveTo(150,150);
ctx.lineTo(150,250);
ctx.lineTo(250,250);
ctx.lineTo(250,150);
ctx.closePath();
/*2.去填充*/
//ctx.stroke();
ctx.fillStyle = 'red';
ctx.fill();
/*在填充的時候回遵循非零環繞規則*/
連接點、線末端類型
var myCanvas = document.querySelector('canvas');
var ctx = myCanvas.getContext('2d');
/*畫平行線*/
ctx.beginPath();
ctx.moveTo(100,100);
ctx.lineTo(200,20);
ctx.lineTo(300,100);
ctx.strokeStyle = 'blue';
ctx.lineWidth = 10;
ctx.lineCap = 'butt';
ctx.lineJoin = 'miter';
ctx.stroke();
ctx.beginPath();
ctx.moveTo(100,200);
ctx.lineTo(200,120);
ctx.lineTo(300,200);
ctx.strokeStyle = 'red';
ctx.lineWidth = 20;
ctx.lineCap = 'square';
ctx.lineJoin = 'bevel';
ctx.stroke();
ctx.beginPath();
ctx.moveTo(100,300);
ctx.lineTo(200,220);
ctx.lineTo(300,300);
ctx.strokeStyle = 'green';
ctx.lineWidth = 30;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.stroke();
繪製虛線
var myCanvas = document.querySelector('canvas');
var ctx = myCanvas.getContext('2d');
/*畫線*/
ctx.moveTo(100,100.5);
ctx.lineTo(300,100.5);
/*虛線是由實線和虛線組成的
setLineDash([5,10]) 含義是實線長度5,虛線長度10,以此排列
當然setLineDash()也可以設置三個參數,會產生不規則的排列方式*/
ctx.setLineDash([20]);
/*獲取虛線的排列方式 獲取的是不重複的那一段的排列方式*/
//console.log(ctx.getLineDash());
/*
lineDashOffset:
如果是正數,設置的偏移是畫線的反方向的偏移
如果是負數,設置的偏移是畫線的方向的偏移
*/
ctx.
lineDashOffset= -20;
ctx.stroke();
繪製由黑到白漸變的矩形
/*線是由點構成的*/
ctx.lineWidth = 30;
for (var i = 0; i < 255; i++) {
ctx.beginPath();
ctx.moveTo(100+i-1,100);
ctx.lineTo(100+i,100);
ctx.strokeStyle = 'rgb('+i+',0,0)';
ctx.stroke();
}
繪製網格
var myCanvas = document.querySelector('canvas');
var ctx = myCanvas.getContext('2d');
/*1.繪製網格*/
/*2.網格的大小*/
var gridSize = 10;
var canvasHeight = ctx.canvas.height;
var canvasWidth = ctx.canvas.width;
/*3.畫多少條X軸方向的線 橫線的條數 畫布高度*/
/*var canvasHeight = myCanvas.height;
var canvasWidth = myCanvas.width;
console.log(canvasHeight);
console.log(canvasWidth);*/
/*console.log(ctx.canvas.width);
console.log(ctx.canvas.height);*/
var xLineTotal = Math.floor(canvasHeight / gridSize);
for (var i = 0; i <= xLineTotal; i++) {
ctx.beginPath();
ctx.moveTo(0, i * gridSize - 0.5 );
ctx.lineTo(canvasWidth, i * gridSize - 0.5);
ctx.strokeStyle = '#eee';
ctx.stroke();
}
/*4.畫多少條Y軸方向的線*/
var yLineTotal = Math.floor(canvasWidth / gridSize);
for (var i = 0; i <= yLineTotal; i++) {
ctx.beginPath();
ctx.moveTo(i*gridSize - 0.5 ,0);
ctx.lineTo(i*gridSize - 0.5 ,canvasHeight);
ctx.strokeStyle = '#eee';
ctx.stroke();
}
/*5.遍歷的形式去畫*/
繪製座標系
var myCanvas = document.querySelector('canvas');
var ctx = myCanvas.getContext('2d');
/*1.繪製座標系*/
/*2.確定原點*/
/*3.確定距離畫布旁邊的距離*/
/*4.確定座標軸的長度*/
/*5.確定箭頭的大小 是個等腰三角形 10 */
/*6.繪製箭頭填充*/
var space = 20;
var arrowSize = 10;
/*計算原點*/
var canvasWidth = ctx.canvas.width;
var canvasHeight = ctx.canvas.height;
var x0 = space;
var y0 = canvasHeight - space;
/*繪製x軸*/
ctx.beginPath();
ctx.moveTo(x0, y0);
ctx.lineTo(canvasWidth - space, y0);
/*箭頭*/
ctx.lineTo(canvasWidth - space - arrowSize, y0 + arrowSize / 2);
ctx.lineTo(canvasWidth - space - arrowSize, y0 - arrowSize / 2);
ctx.lineTo(canvasWidth - space, y0);
ctx.fill();
ctx.stroke();
/*繪製y軸*/
ctx.beginPath();
ctx.moveTo(x0, y0);
ctx.lineTo(space, space);
/*箭頭*/
ctx.lineTo(space + arrowSize / 2, space + arrowSize);
ctx.lineTo(space - arrowSize / 2, space + arrowSize);
ctx.lineTo(space, space);
ctx.fill();
ctx.stroke();
繪製點
var myCanvas = document.querySelector('canvas');
var ctx = myCanvas.getContext('2d');
/*1.繪製點*/
/*2.點的尺寸*/
/*3.以座標中心繪製點*/
/*點座標*/
var coordinate = {
x:100,
y:100
}
/*點尺寸*/
var dottedSize = 10;
ctx.moveTo(coordinate.x - dottedSize / 2,coordinate.y - dottedSize / 2);
ctx.lineTo(coordinate.x + dottedSize / 2,coordinate.y - dottedSize / 2);
ctx.lineTo(coordinate.x + dottedSize / 2,coordinate.y + dottedSize / 2);
ctx.lineTo(coordinate.x - dottedSize / 2,coordinate.y + dottedSize / 2);
ctx.closePath();
ctx.fill();
繪製折線圖
/*1.構造函數*/
var LineChart = function (ctx) {
/*獲取繪圖工具*/
this.ctx = ctx || document.querySelector('canvas').getContext('2d');
/*畫布的大小*/
this.canvasWidth = this.ctx.canvas.width;
this.canvasHeight = this.ctx.canvas.height;
/*網格的大小*/
this.gridSize = 10;
/*座標系的間距*/
this.space = 20;
/*座標原點*/
this.x0 = this.space;
this.y0 = this.canvasHeight - this.space;
/*箭頭的大小*/
this.arrowSize = 10;
/*繪製點*/
this.dottedSize = 6;
/*點的座標 和數據有關係 數據可視化*/
}
/*2.行爲方法*/
LineChart.prototype.init = function (data) {
this.drawGrid();
this.drawAxis();
this.drawDotted(data);
};
/*繪製網格*/
LineChart.prototype.drawGrid = function () {
/*x方向的線*/
var xLineTotal = Math.floor(this.canvasHeight / this.gridSize);
this.ctx.strokeStyle = '#eee';
for (var i = 0; i <= xLineTotal; i++) {
this.ctx.beginPath();
this.ctx.moveTo(0, i * this.gridSize - 0.5);
this.ctx.lineTo(this.canvasWidth, i * this.gridSize - 0.5);
this.ctx.stroke();
}
/*y方向的線*/
var yLineTotal = Math.floor(this.canvasWidth / this.gridSize);
for (var i = 0; i <= yLineTotal; i++) {
this.ctx.beginPath();
this.ctx.moveTo(i * this.gridSize - 0.5, 0);
this.ctx.lineTo(i * this.gridSize - 0.5, this.canvasHeight);
this.ctx.stroke();
}
};
/*繪製座標系*/
LineChart.prototype.drawAxis = function () {
/*X軸*/
this.ctx.beginPath();
this.ctx.strokeStyle = '#000';
this.ctx.moveTo(this.x0, this.y0);
this.ctx.lineTo(this.canvasWidth - this.space, this.y0);
this.ctx.lineTo(this.canvasWidth - this.space - this.arrowSize, this.y0 + this.arrowSize / 2);
this.ctx.lineTo(this.canvasWidth - this.space - this.arrowSize, this.y0 - this.arrowSize / 2);
this.ctx.lineTo(this.canvasWidth - this.space, this.y0);
this.ctx.stroke();
this.ctx.fill();
/*Y軸*/
this.ctx.beginPath();
this.ctx.strokeStyle = '#000';
this.ctx.moveTo(this.x0, this.y0);
this.ctx.lineTo(this.space, this.space);
this.ctx.lineTo(this.space + this.arrowSize / 2, this.space + this.arrowSize);
this.ctx.lineTo(this.space - this.arrowSize / 2, this.space + this.arrowSize);
this.ctx.lineTo(this.space, this.space);
this.ctx.stroke();
this.ctx.fill();
};
/*繪製所有點*/
LineChart.prototype.drawDotted = function (data) {
/*1.數據的座標 需要轉換 canvas座標*/
/*2.再進行點的繪製*/
/*3.把線連起來*/
var that = this;
/*記錄當前座標*/
var prevCanvasX = 0;
var prevCanvasY = 0;
data.forEach(function (item, i) {
/* x = 原點的座標 + 數據的座標 */
/* y = 原點的座標 - 數據的座標 */
var canvasX = that.x0 + item.x;
var canvasY = that.y0 - item.y;
/*繪製點*/
that.ctx.beginPath();
that.ctx.moveTo(canvasX - that.dottedSize / 2, canvasY - that.dottedSize / 2);
that.ctx.lineTo(canvasX + that.dottedSize / 2, canvasY - that.dottedSize / 2);
that.ctx.lineTo(canvasX + that.dottedSize / 2, canvasY + that.dottedSize / 2);
that.ctx.lineTo(canvasX - that.dottedSize / 2, canvasY + that.dottedSize / 2);
that.ctx.closePath();
that.ctx.fill();
/*點的連線*/
/*當時第一個點的時候 起點是 x0 y0*/
/*當時不是第一個點的時候 起點是 上一個點*/
if(i == 0){
that.ctx.beginPath();
that.ctx.moveTo(that.x0,that.y0);
that.ctx.lineTo(canvasX,canvasY);
that.ctx.stroke();
}else{
/*上一個點*/
that.ctx.beginPath();
that.ctx.moveTo(prevCanvasX,prevCanvasY);
that.ctx.lineTo(canvasX,canvasY);
that.ctx.stroke();
}
/*記錄當前的座標,下一次要用*/
prevCanvasX = canvasX;
prevCanvasY = canvasY;
});
};
/*3.初始化*/
var data = [
{
x: 100,
y: 120
},
{
x: 200,
y: 160
},
{
x: 300,
y: 240
},
{
x: 400,
y: 120
},
{
x: 500,
y: 80
}
];
var lineChart = new LineChart();
lineChart.init(data);
參考文檔
Canvas圖形繪製
矩形繪製
-
rect(x,y,w,h) 沒有獨立路徑
-
strokeRect(x,y,w,h) 有獨立路徑,不影響別的繪製
-
fillRect(x,y,w,h) 有獨立路徑,不影響別的繪製
- clearRect(x,y,w,h) 擦除矩形區域
var myCanvas = document.querySelector('canvas');
var ctx = myCanvas.getContext('2d');
/*繪製矩形路徑 不是獨立路徑*/
/*ctx.rect(100,100,200,100);
ctx.fillStyle = 'green';
ctx.stroke();
ctx.fill();*/
/*繪製矩形 有自己的獨立路徑*/
//ctx.strokeRect(100,100,200,100);
ctx.fillRect(100,100,200,100);
/*清除矩形的內容*/
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
繪製漸變矩形
var myCanvas = document.querySelector('canvas');
var ctx = myCanvas.getContext('2d');
/*也可以使用一個漸變的方案了填充矩形*/
/*創建一個漸變的方案*/
/*漸變是有長度的*/
/*x0 y0 起始點 x1 y1 結束點*/
var linearGradient = ctx.createLinearGradient(100,100,500,100);
linearGradient.addColorStop(0,'pink');
//linearGradient.addColorStop(0.5,'red');
linearGradient.addColorStop(1,'blue');
ctx.fillStyle = linearGradient;
ctx.fillRect(100,100,400,100);
圓弧繪製
- 弧度概念
-
arc()
-
x 圓心橫座標
-
y 圓心縱座標
-
r 半徑
-
startAngle 開始角度
-
endAngle 結束角度
- anticlockwise 是否逆時針方向繪製(默認false表示順時針;true表示逆時針)
-
繪製四分之一個圓弧
var myCanvas = document.querySelector('canvas');
var ctx = myCanvas.getContext('2d');
/*1.確定圓心 座標 x y*/
/*2.確定圓半徑 r */
/*3.確定起始繪製的位置和結束繪製的位置 確定弧的長度和位置 startAngle endAngle 弧度*/
/*4.取得繪製的方向 direction 默認是false順時針。*/
/*在中心位置畫一個半徑150px的圓弧左下角*/
var w = ctx.canvas.width;
var h = ctx.canvas.height;
ctx.arc(w/2,h/2,150,0,Math.PI/2);
ctx.stroke();
繪製扇形
var myCanvas = document.querySelector('canvas');
var ctx = myCanvas.getContext('2d');
/*在中心位置畫一個半徑150px的圓弧右上角 扇形 邊 填充 */
var w = ctx.canvas.width;
var h = ctx.canvas.height;
/*把起點放到圓心位置*/
ctx.moveTo(w/2,h/2);
ctx.arc(w/2,h/2,150,0,-Math.PI/2,true);
/*閉合路徑*/
ctx.closePath();
tx.stroke();
ctx.fill();
繪製圓分成六等分顏色隨機
var myCanvas = document.querySelector('canvas');
var ctx = myCanvas.getContext('2d');
var w = ctx.canvas.width;
var h = ctx.canvas.height;
/*分成幾等分*/
var num = 360;
/*一份多少弧度*/
var angle = Math.PI * 2 / num;
/*原點座標*/
var x0 = w / 2;
var y0 = h / 2;
/*獲取隨機顏色*/
var getRandomColor = function () {
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
return 'rgb(' + r + ',' + g + ',' + b + ')';
}
/*上一次繪製的結束弧度等於當前次的起始弧度*/
//var startAngle = 0;
for (var i = 0; i < num; i++) {
var startAngle = i * angle;
var endAngle = (i + 1) * angle;
ctx.beginPath();
ctx.moveTo(x0, y0);
ctx.arc(x0, y0, 150, startAngle, endAngle);
/*隨機顏色*/
ctx.fillStyle = getRandomColor();
ctx.fill();
}
根據數據繪製餅圖
var myCanvas = document.querySelector('canvas');
var ctx = myCanvas.getContext('2d');
/*1.根據37期的年齡分佈繪製餅圖*/
/*2.準備統計的數據*/
/*15-20歲 6個*/
/*20-25歲 30個*/
/*25-30歲 10個*/
/*30-35歲 8個*/
var data = [6, 30, 10, 8];
/*3.在餅圖表示出來*/
/*4.需要把數據轉出弧度*/
var angleList = [];
var total = 0;
data.forEach(function (item, i) {
total += item;
});
console.log(total);
/*第二是轉換成弧度的時候就可以去繪製扇形 減少一次遍歷*/
data.forEach(function (item, i) {
var angle = Math.PI * 2 * (item/total);
angleList.push(angle);
});
console.log(angleList);
/*5.根據弧度繪製扇形*/
var w = ctx.canvas.width;
var h = ctx.canvas.height;
var x0 = w/2;
var y0 = h/2;
/*獲取隨機顏色*/
var getRandomColor = function () {
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
return 'rgb(' + r + ',' + g + ',' + b + ')';
}
var startAngle = 0;
angleList.forEach(function (item,i) {
/*上一次繪製的結束弧度等於當前次的起始弧度*/
var endAngle = startAngle + item;
ctx.beginPath();
ctx.moveTo(x0,y0);
ctx.arc(x0,y0,150,startAngle,endAngle);
ctx.fillStyle = getRandomColor();
ctx.fill();
/*記錄當前的結束位置作爲下一次的起始位置*/
startAngle = endAngle;
});
繪製文本
- ctx.font = '微軟雅黑' 設置字體
- strokeText()
- fillText(text,x,y,maxWidth)
- text 要繪製的文本
- x,y 文本繪製的座標(文本左下角)
- maxWidth 設置文本最大寬度,可選參數
- ctx.textAlign文本水平對齊方式,相對繪製座標來說的
- left
- center
- right
- start 默認
- end
- ctx.textBaseline 設置基線(垂直對齊方式 )
- top 文本的基線處於文本的正上方,並且有一段距離
- middle 文本的基線處於文本的正中間
- bottom 文本的基線處於文本的證下方,並且有一段距離
- hanging 文本的基線處於文本的正上方,並且和文本粘合
- alphabetic 默認值,基線處於文本的下方,並且穿過文字
- ideographic 和bottom相似,但是不一樣
- measureText() 獲取文本寬度obj.width
var myCanvas = document.querySelector('canvas');
var ctx = myCanvas.getContext('2d');
/*1.在畫布的中心繪製一段文字*/
/*2.申明一段文字*/
var str = '您吃-,了嗎';
/*3.確定畫布的中心*/
var w = ctx.canvas.width;
var h = ctx.canvas.height;
/*4.畫一個十字架在畫布的中心*/
ctx.beginPath();
ctx.moveTo(0, h / 2 - 0.5);
ctx.lineTo(w, h / 2 - 0.5);
ctx.moveTo(w / 2 - 0.5, 0);
ctx.lineTo(w / 2 - 0.5, h);
ctx.strokeStyle = '#eee';
ctx.stroke();
/*5.繪製文本*/
ctx.beginPath();
ctx.strokeStyle = '#000';
var x0 = w/2;
var y0 = h/2;
/*注意:起點位置在文字的左下角*/
/*有文本的屬性 尺寸 字體 左右對齊方式 垂直對齊的方式*/
ctx.font = '40px Microsoft YaHei';
/*左右對齊方式 (center left right start end) 基準起始座標*/
ctx.textAlign = 'center';
/*垂直對齊的方式 基線 baseline(top,bottom,middle) 基準起始座標*/
ctx.textBaseline = 'middle';
//ctx.strokeText(str,x0,y0);
ctx.fillText(str,x0,y0);
/*6.畫一個下劃線和文字一樣長*/
ctx.beginPath();
/*獲取文本的寬度*/
console.log(ctx.measureText(str));
var width = ctx.measureText(str).width;
關於text-align和direction
//左對齊:
如果 textAlign = left
如果textAlign = start && direction = 'ltr'
如果 textAlign = end && direction = 'rtl'
讓元素的錨點位於行內盒子的左邊,並且左對齊
//右對齊:
如果 textAlign = right
如果 textAlign = end && direction = 'ltr'
如果 textAlign = start && direction = 'rtl'
讓元素的錨點位於行內盒子的左邊,並且右對齊
//居中對齊:
如果textAlign = center,讓元素的錨點處於行內元素的中心並且居中對齊
//關於ltr和rtl:
direction :ltr:佈局方向是left to right
rirection :rtl 佈局方向是right to left
#注意點:
<div>
<img src=”images/1.jpg”>
<img src=”images/2.jpg”>
</div>
1. 在設置div的text-align:left direction:ltr/rtl的情況下,ltr和rtl下兩張圖片的前後位置會發生改變;但是如果div中加的是兩個span,這兩個span的位置不會發生變化。
2.當div中的行內元素是<img>, <button>, <input>, <video>, <object>等標籤的時候,ltr和rtl下元素的位置會發生交換。
3.w3c參考文檔
https://www.w3.org/TR/2dcontext/
做動畫
繪製圖片
- drawImage()
- 三個參數drawImage(img,x,y)
- img 圖片對象、canvas對象、video對象
- x,y 圖片繪製的左上角
- 五個參數drawImage(img,x,y,w,h)
- img 圖片對象、canvas對象、video對象
- x,y 圖片繪製的左上角
- w,h 圖片繪製尺寸設置(圖片縮放,不是截取)
- 九個參數drawImage(img,x,y,w,h,x1,y1,w1,h1)
- img 圖片對象、canvas對象、video對象
- x,y,w,h 圖片中的一個矩形區域
- x1,y1,w1,h1 畫布中的一個矩形區域
- 三個參數drawImage(img,x,y)
序列幀動畫
- 繪製精靈圖
- 動起來
- 控制邊界
- 鍵盤控制
座標變換
- 平移 移動畫布的原點
- translate(x,y) 參數表示移動目標點的座標
- 縮放
- scale(x,y) 參數表示寬高的縮放比例
- 旋轉
- rotate(angle) 參數表示旋轉角度
案例
繪製圖片
var myCanvas = document.querySelector('canvas');
var ctx = myCanvas.getContext('2d');
/*1.加載圖片到內存即可*/
/*var img = document.createElement('img');
img.src = 'image/01.jpg';*/
/*創建對象*/
var image = new Image();
/*綁定加載完成事件*/
image.onload = function () {
/*實現圖片繪製*/
console.log(image);
/*繪製圖片的三種方式*/
/*3參數*/
/*圖片對象*/
/*繪製在畫布上的座標 x y*/
//ctx.drawImage(image,100,100);
/*5個參數*/
/*圖片對象*/
/*繪製在畫布上的座標 x y*/
/*是圖片的大小 不是裁剪 是縮放*/
//ctx.drawImage(image,100,100,100,100);
/*9個參數*/
/*圖片對象*/
/*圖片上定位的座標:從什麼位置開始顯示圖片 x y */
/*在圖片上截取多大的區域:從上面圖片的座標開始截取多大的顯示區域 w h*/
/*繪製在畫布上的座標 x y*/
/*是圖片的大小:將要顯示的圖片進行縮放*/
ctx.drawImage(image,400,400,400,400,200,200,100,100);
};
/*設置圖片路徑*/
image.src = 'image/02.jpg';
繪製幀動畫
var myCanvas = document.querySelector('canvas');
var ctx = myCanvas.getContext('2d');
var image = new Image();
image.onload = function () {
/*圖片加載完成*/
/*動態的去獲取當前圖片的尺寸*/
var imageWidth = image.width;
var imageHeight = image.height;
/*計算出每一個小人物的尺寸*/
var personWidth = imageWidth/4;
var personHeight = imageHeight/4;
/*位截取圖片*/
/*幀動畫 在固定的時間間隔更換顯示的圖片 根據圖片的索引*/
var index = 0;
/*繪製在畫布的中心*/
/*圖片繪製的起始點*/
var x0 = ctx.canvas.width /2 - personWidth / 2;
var y0 = ctx.canvas.height /2 - personHeight / 2;
ctx.drawImage(image,0,0,personWidth,personHeight,x0,y0,personWidth,personHeight);
setInterval(function () {
index ++;
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
ctx.drawImage(image,index * personWidth,0,personWidth,personHeight,x0,y0,personWidth,personHeight);
if(index >= 3){
index = 0;
}
},1000);
};
方向鍵控制行走小人
<script>
var Person = function (ctx) {
/*繪製工具*/
this.ctx = ctx || document.querySelector('canvas').getContext('2d');
/*圖片路徑*/
this.src = 'image/04.png';
/*畫布的大小*/
this.canvasWidth = this.ctx.canvas.width;
this.canvasHeight = this.ctx.canvas.height;
/*行走相關參數*/
this.stepSzie = 10;
/* 0 前 1 左 2 右 3 後 和圖片的行數包含的圖片對應上*/
this.direction = 0;
/*x軸方向的偏移步數*/
this.stepX = 0;
/*y軸方向的偏移步數*/
this.stepY = 0;
/*初始化方法*/
this.init();
};
Person.prototype.init = function () {
var that = this;
var image = new Image();
image.onload = function () {
/*image.onload方法中的this是當前image對象
因爲之前that=this,所以此時image.onload方法中的 that代表當前Person對象
*/
/*圖片的大小*/
that.imageWidth = image.width;
that.imageHeight = image.height;
/*人物的大小*/
that.personWidth = that.imageWidth / 4;
that.personHeight = that.imageHeight / 4;
/*繪製圖片的起點*/
that.x0 = that.canvasWidth / 2 - that.personWidth / 2;
that.y0 = that.canvasHeight / 2 - that.personHeight / 2;
/*2.默認繪製在中心位置正面朝外*/
that.ctx.drawImage(image,
0,0,
that.personWidth,that.personHeight,
that.x0,that.y0,
that.personWidth,that.personHeight);
/*3.能通過方向鍵去控制人物行走*/
that.index = 0;
document.onkeydown = function (e) {
if(e.keyCode == 40){
that.direction = 0;
if(that.stepY <= that.canvasHeight/2/that.stepSzie) {
that.stepY++;
that.drawImage(image);
}
/*前*/
}else if(e.keyCode == 37){
that.direction = 1;
if(that.stepX >= -that.canvasWidth/2/that.stepSzie) {
that.stepX--;
that.drawImage(image);
}
/*左*/
}else if(e.keyCode == 39){
that.direction = 2;
if(that.stepX <= that.canvasWidth/2/that.stepSzie) {
that.stepX++;
that.drawImage(image);
}
/*右*/
}else if(e.keyCode == 38){
that.direction = 3;
if(that.stepY >= -that.canvasHeight/2/that.stepSzie) {
that.stepY--;
that.drawImage(image);
}
/*後*/
}
}
};
image.src = this.src;
}
/*繪製圖片*/
Person.prototype.drawImage = function (image) {
this.index ++;
/*清除畫布*/
this.ctx.clearRect(0,0,this.canvasWidth,this.canvasHeight);
/*繪圖*/
/*在精靈圖上的定位 x 索引*/
/*在精靈圖上的定位 y 方向*/
this.ctx.drawImage(image,
this.index * this.personWidth,this.direction * this.personHeight,
this.personWidth,this.personHeight,
this.x0 + this.stepX * this.stepSzie ,this.y0 + this.stepY * this.stepSzie,
this.personWidth,this.personHeight);
/*如果索引超出了 變成0*/
if(this.index >= 3){
this.index = 0;
}
};
new Person();
</script>
座標變化
var myCanvas = document.querySelector('canvas');
var ctx = myCanvas.getContext('2d');
//ctx.translate(100,100); //讓座標系平移100,100(座標系原點會發生變化)
//ctx.scale(0.5,1); //讓座標系x方向縮放0.5 (座標系刻度會發生變化)
//ctx.rotate(Math.PI/6); //跟隨座標系遠點旋轉30°
var startAngle = 0;
ctx.translate(150,150); //座標系平移150,150
setInterval(function () {
startAngle += Math.PI/180;
ctx.rotate(startAngle);
ctx.strokeRect(0,0,100,100);//因爲上面ctx.translate(150,150) 平移了150像素,所以導致canvas的座標系也平移了150,從而讓下面旋轉的時候會沿着新的座標系的原點進行旋轉
},500);