HTML5邊玩邊學(6):汽車人,變形......

作者: 左洸  來源: 博客園  發布時間: 2010-10-09 17:59  閱讀: 1327 次  推薦: 0   原文鏈接   [收藏]  

  一、狀態及其保存和恢復

  在這一節開始之前,我們要先理解一下什么是狀態以及狀態的保存和恢復。玩過 MFC 編程的人經常能碰到這樣的代碼:pOldPen=pDC->SelectObject(pNewPen)

  我們在選擇一個新畫筆對象的同時,總是要保存住舊畫筆對象,為什么要這樣做呢?因為新畫筆對象只是臨時用一下,等用完了,我們想恢復到原來的畫筆配置時,如果舊的配置事先沒有被保存,這些配置就丟失了,也就沒辦法恢復了。

  在 HTML5 繪圖中,某一刻的狀態就是當前這一刻上下文對象的一系列屬性的配置值,只是,決定一個畫筆狀態的屬性比較少,如顏色、粗細、線型之類的,而確定上下文狀態的屬性比較多,包括下面這些:

  1、當前上下文對象的移動、旋轉、縮放配置。

  2、當前上下文對象的 strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation 屬性值。

  3、當前上下文對象的裁剪路徑配置。

  上面這一系列配置決定了當前這一刻上下文對象的狀態,其中移動、旋轉、縮放、globalCompositeOperation(組合)、裁剪下面我們馬上會講到。

  二、狀態的保存與恢復

  上面我們說某一刻的狀態由那么多屬性決定,我們要保存這一刻的狀態就要把這些屬性值一個一個都保存,恢復的時候在一個一個都設置回去,那也太麻煩了。確實是這樣的,所以上下文對下提供了了兩個簡單的方法,對狀態進行保存和恢復,他們是:save( ) 和 restore( ),save 和 restore 方法可以多次調用,每調用一次 save 方法,調用時的狀態(即一系列屬性值)就壓入一個棧中。每調用一次 restore 方法,最后一次 save 的狀態就被恢復,即出棧。想象一下彈匣,第一顆被發射出去的子彈,總是最后一個被壓入彈匣的。

  三、變型

  1、移動:translate(dx,dy)

  這個方法看上去很簡單,其實它包含了一定的數學含義,你可以認為是整個坐標系的原點發生了移動,新坐標系下任意一點(x,y)相當于原坐標系下的坐標為:

  x'=x+dx
  y'=y+dy

  如果我們調用 ctx.translate(5,8) 改變上下文對象的坐標系狀態,然后在新狀態下的點(3,2)繪圖,相當于圖像被繪制到了原狀態下的點(8,10)處,即:

  x'=5+3=8
  y'=5+2=10

  也許你會問,為什么要那么麻煩,直接在(8,10)處繪制比行嗎?比如把:

  ctx.translate(5,8)
  ctx.drawImage(img,3,2)

  改成:

  ctx.drawImage(img,8,10)

  這樣不是更簡單、更直接嗎?

  我的理解是,移動更多的情況下是為其他圖形變換服務的,恰當的改變坐標原點可以讓圖形學計算更好理解,并帶來很大方便,下面我舉個簡單的例子,假如:

  有一條線段 ,是 x 軸正向上的一小段:y = 0 (1 <= x <= 3),如果以坐標原點為圓心,逆時針旋轉90度,則線段與 y 軸正向重合,旋轉后的線段為:x = 0 (1 <= y <= 3)。

  但是我們不可能每次旋轉都以原點為圓心進行旋轉,假如我們以線段的一個端點(1,0)為圓心進行旋轉,我們怎么才能得到旋轉后線段上每一點的坐標值呢?其實這個過程可以分為三步:

  第一步:移動原點坐標到(1,0),新的線段依然在 x 軸上,但是方程變為了:y = 0 (0 <= x <= 2)。

  第二步:以新坐標系的原點為圓心進行旋轉,得到新坐標系下的線段 x = 0 (0 <= y <= 2)。

  第三步:將新坐標系的原點移動到新坐標系下(-1,0)處,即將原點恢復到原來的位置,此時的線段為:x = 1 (0 <= y <= 2)。

  第三步所得到的線段就是最后需要繪制的線段。

  從這個例子我們可以看出來,即使在這么簡單的情況下,如果不移動坐標原點來直接計算旋轉后的圖形,也是比較困難的。提示:當你移動坐標原點之前,千萬別忘了保存狀態,當然,繪制完畢后也別放了恢復狀態。

  2、縮放 scale(sx, sy)

  這個同樣很簡單,sx, sy 是縮放比例因子,縮放后新坐標系下任意一點 (x,y) 相當于原坐標系下的坐標為:

  x' = x * sx
  y' = y * sy

  同樣,改變坐標系統總是不要忘記保存和恢復狀態。

  3、旋轉 rotate(A)

  angle 是旋轉角度,旋轉后新坐標系下任意一點 (x,y) 相當于原坐標系下的坐標為:

  x' = x cosA - y sinA
  y' = x sinA + y cosA

  同樣,改變坐標系統總是不要忘記保存和恢復狀態。

  4、變形 transform(m11, m12, m21, m22, dx, dy)

  其實前面講的移動、縮放、旋轉都是變形的特例,transform 方法的六個參數組成了一個變形矩陣,如下:

m11 m21 dx
m12 m22 dy
0 0 1

  調用 transform 方法就相當于用這些參數為上下文對象設置了新的變形矩陣,關于變形矩陣的具體內容可以參照圖形學相關資料,下面給出幾個簡單特例:

  移動 translate(dx,dy):相當于 transform(1,0,0,1,dx,dy)。

  縮放 scale(sx,xy):相當于 transform(sx,0,0,sy,0,0)。

  旋轉 rotate(A):相當于 transform(cosA,sinA,-sinA,cosA,0,0)。

  以 (dx,dy) 為基準點旋轉角度 A:transform(cosA, sinA, -sinA, cosA, dx(1-cosA) + dysinA, dy(1-cosA) - dxsinA)。

  以 (dx,dy) 為基準點進行 (sx,sy)比例縮放:transform(sx, 0, 0, sy, dx(1-sx), dy(1-sy))。

  還有很多其他更復雜的變形,大家可以參考圖形學相關資料。下面給出一個基準點變形的例子,鼠標在圖像上的某點保持按下狀態,圖像就會以該點為基準點進行縮放或者旋轉,松開按鈕后圖像復原。提示:即縮放又旋轉這個例子,并沒有使用變形矩陣,而是用了四步簡單變形復合而成。效果請查看文章下面全部代碼。

  四、組合

  所謂組合就是一個圖形繪制在另一個圖形之上,會出現什么效果。默認的情況下是上面的圖形覆蓋了下面的圖形,稱之為 source-over 。上下文對象總共十二中組合類型,屬性 globalCompositeOperation 被用來設置組合類型,如下:

  globalCompositeOperation = type

  type 是下面 12 種字符串值之一:

  注意:上面所有例子中,藍色方塊是先繪制的,即“已有的 canvas 內容”,紅色圓形是后面繪制,即“新圖形”。

  五、裁剪路徑

  在第一篇文章中我們就介紹了上下文對象的兩大類繪制方法,即繪制線條的 stroke 系列方法和填充區域的 fill 系列方法,其實,上下文對象還有一類繪制方法叫做裁剪 clip 。

  什么是裁剪呢?打個不恰當的比方吧,你用一塊布把電視機屏幕遮住了,這時候電視機屏幕上的任何變化你都看不見了。但是,如果你布上裁剪出一塊區域,那么至少這塊區域里的屏幕變化你能看見。當然裁剪區域之外的屏幕也在不停地變化(即也在重新繪制),只是你看不見罷了。這就是所謂的裁剪,平常在處理圖像時經常會遇到這種需求。那么什么又是裁剪路徑呢?上面說要在布上裁剪出一塊區域,這塊區域是怎么來的呢?

  這塊區域是在裁剪動作 clip 之前,由繪圖路徑設定的,他可以是方形、圓形、五星形和其他任何可以繪制的輪廓形狀。所以,裁剪路徑其實就是繪圖路徑,只不過這個路徑不是拿來繪圖的,而是設定顯示區域和遮擋區域的一個分界線。如果你不明白什么是繪圖路徑,在前的文章 HTML5邊玩邊學(2):基礎繪圖 中有介紹。

  下面的例子用了兩種方法進行裁剪。第一種方法顯示一來回移動的圓形裁剪區域,大體流程如下:

  1、清空畫布

  2、改變圓心位置

  3、在新的圓心位置處設置一個圓形的裁剪區域

  4、在畫布上繪制美女圖像

  由于我們不停地在新位置處設定裁剪區域,我們就能看見裁剪區域在移動,而裁剪區域之外的圖像并沒有顯示出來。我們用 clip 方法設置裁剪區域,之后繪制的圖形只能顯示裁剪區域內的一部分,而裁剪區域之外總是顯示畫布的背景色。假如并不想完全遮擋裁剪區域之外的圖像,比如我們想讓裁剪區域之內的圖像完全顯示出來,但是裁剪區域之外的圖像以半透明的方式顯示出來,該怎么做呢?這就要用到我們上面說的的組合知識了。第二中方法顯示半透明的遮擋,大體思路如下:

  1、清空畫布。

  2、將畫布的所有區域用一種半透明的顏色填充,這里我用的是灰色,透明度0.9。

  3、改變圓心位置。

  4、在新的圓心位置處以 XOR 方式繪制圓,這樣和圓形重疊的部分將被擦除掉。這時候我們得到的圖形效果是一個半透明的畫布,上面有一塊完全透明的圓形區域。

  5、 在第 4 步的基礎上,以 destination-over 方式繪制美女圖像,這時候美女圖像將會出現在第 4 步圖形效果的下方,想象一下,正好是我們想要的效果吧?!

  效果請見代碼如下:

 
<canvas id="canvas1" width="250" height="300"
onmousedown="trans.transform(event);"
onmouseup="trans.init(event);"
onmousemove="trans.translate(event);"
style="background-color:black">
你的瀏覽器不支持 &lt;canvas&gt;標簽,請使用 Chrome 瀏覽器 或者 FireFox 瀏覽器
</canvas><br/>
<input type="radio" name="r" id="r1" checked="checked">移動——在圖像上按住鼠標并移動<br />
<input type="radio" name="r" id="r2">基準點縮放——在圖像某點處按住鼠標<br />
<input type="radio" name="r" id="r3">基準點旋轉——在圖像某點處按住鼠標<br /& gt;
<input type
="radio" name="r" id="r4">基準點縮放同時旋轉——在圖像某點處按住鼠標< br />

<canvas id="canvas3" width="250" height="300" style="background-color:black">
你的瀏覽器不支持 &lt;canvas&gt;標簽,請使用 Chrome 瀏覽器 或者 FireFox 瀏覽器
</canvas><br/>
<input type="button" onclick="move(1);" value="移動裁剪區域">
<input type="button" onclick="move(2);" value="移動蒙版">
<input type="button" onclick="stop();" value="停止移動"><br />

<div>
<table>
<tr>
<td><canvas id="tut0" width="125" height="125"></canvas><br/><label id="lab0"></label></td>
<td><canvas id="tut1" width="125" height="125"></canvas><br/><label id="lab1"></label></td>
<td><canvas id="tut2" width="125" height="125"></canvas><br/><label id="lab2"></label></td>
<td><canvas id="tut3" width="125" height="125"></canvas><br/><label id="lab3"></label></td>
</tr>
<tr>
<td><canvas id="tut4" width="125" height="125"></canvas><br/><label id="lab4"></label></td>
<td><canvas id="tut5" width="125" height="125"></canvas><br/><label id="lab5"></label></td>
<td><canvas id="tut6" width="125" height="125"></canvas><br/><label id="lab6"></label></td>
<td><canvas id="tut7" width="125" height="125"></canvas><br/><label id="lab7"></label></td>
</tr>
<tr>
<td><canvas id="tut8" width="125" height="125"></canvas><br/><label id="lab8"></label></td>
<td><canvas id="tut9" width="125" height="125"></canvas><br/><label id="lab9"></label></td>
<td><canvas id="tut10" width="125" height="125"></canvas><br/><label id="lab10"></label></td>
<td><canvas id="tut11" width="125" height="125"></canvas><br/><label id="lab11"></label></td>
</tr>
</table>
</div>


<script type="text/javascript">
//美女圖的 Base64 編碼
IMG_SRC='data:image/gif;base64,/9j /4QDfRXhpZgAASUkqAAgAAAAFABIBAwA......';//省略四十字節

//==========================================
//基準點變形類
//==========================================
function Transform(){
//獲取畫布對象
this.ctx = document.getElementById("canvas1").getContext("2d");
//創建圖像對象
this.img=new Image();
//指定圖像源
this.img.src=IMG_SRC;
this.interval = null;
//鼠標按鈕狀態
this.pressed=false;
this.init();
}


//初始化圖形
Transform.prototype.init=function(){
//鼠標按鈕狀態
this.pressed=false;
//停止計時器
if(this.interval) clearInterval(this.interval);
//變化值
this.delta = 0.06;
//清空
this.ctx.clearRect(0,0,250,300);
//重繪
this.paint();
}


//繪制圖像
Transform.prototype.paint=function(){
var that=this;
var img=this.img
if(img.complete)
that.ctx.drawImage(img,
0,0);
else
var interval = setInterval(function(){
if(img.complete){
that.ctx.drawImage(img,
0,0);
clearInterval(interval);
}
},
300);
}


//鼠標按鈕按下后,開始變形
Transform.prototype.transform = function(){
//獲取基準點
this.dx=event.offsetX;
this.dy=event.offsetY;
//獲取基準點
this.startx=event.offsetX;
this.starty=event.offsetY;
//初始縮放比例
this.sc=1;
//初旋轉角度
this.angle=0;

var that=this;
if(document.getElementById("r1").checked)
//鼠標按鈕狀態
this.pressed=true;
else if(document.getElementById("r2").checked)
this.interval = setInterval(function(){that.scale()},50);
else if((document.getElementById("r3").checked))
this.interval = setInterval(function(){that.rotate()},50);
else
this.interval = setInterval(function(){that.scaleAndRotate()},50);
}


//移動
Transform.prototype.translate = function(){
this.ddx=event.offsetX-this.startx;
this.ddy=event.offsetY-this.starty;
if(this.pressed){
//清空
this.ctx.clearRect(0,0,250,300);
//保存狀態
this.ctx.save();
//平移
this.ctx.translate(this.ddx,this.ddy);
//重繪
this.paint();
//繪制基準點
this.ctx.fillStyle="red";
this.ctx.fillRect(this.dx-5,this.dy-5,10,10);
//恢復狀態
this.ctx.restore();
}
}


//縮放變形
Transform.prototype.scale = function(){
//清空
this.ctx.clearRect(0,0,250,300);
//改變縮放比例
this.sc=this.sc - this.delta;
if(this.sc<0.2 || this.sc>2)
this.delta = -this.delta;
//保存狀態
this.ctx.save();
//以 (dx,dy) 為基準點進行 (sx,sy)比例縮放:transform(sx, 0, 0, sy, dx(1- sx), dy(1-sy))
this.ctx.transform(this.sc, 0, 0, this.sc, this.dx*(1-this.sc), this.dy*(1-this.sc))
//用新的變形矩陣重繪
this.paint();
//繪制基準點
this.ctx.fillStyle="red";
this.ctx.fillRect(this.dx-5,this.dy-5,10,10);
//恢復狀態
this.ctx.restore();
}


//旋轉變形
Transform.prototype.rotate = function(){
//清空
this.ctx.clearRect(0,0,250,300);
//改變縮放比例
var PI = Math.PI;
this.angle=this.angle + PI/60;
//保存狀態
this.ctx.save();
//以 (dx,dy) 為基準點旋轉角度 A:transform(cosA, sinA, -sinA, cosA, dx(1- cosA) + dysinA, dy(1-cosA) - dxsinA)
this.ctx.transform(Math.cos(this.angle), Math.sin(this.angle),
-Math.sin(this.angle), Math.cos(this.angle),
this.dx*(1-Math.cos(this.angle)) + this.dy*Math.sin(this.angle),
this.dy*(1-Math.cos(this.angle)) - this.dx*Math.sin(this.angle))
//用新的變形矩陣重繪
this.paint();
//繪制基準點
this.ctx.fillStyle="red";
this.ctx.fillRect(this.dx-5,this.dy-5,10,10);
//恢復狀態
this.ctx.restore();
}


//即縮放又旋轉變形,沒有使用變形矩陣
Transform.prototype.scaleAndRotate = function(){
//清空
this.ctx.clearRect(0,0,250,300);
//改變縮放比例
this.sc=this.sc - this.delta;
if(this.sc<0.2 || this.sc>2)
this.delta = -this.delta;
var PI = Math.PI;
this.angle=this.angle + PI/60;
//保存狀態
this.ctx.save();
//先移動原點到基點
this.ctx.translate(this.dx,this.dy);
this.ctx.scale(this.sc,this.sc);
this.ctx.rotate(this.angle);
this.ctx.translate(-this.dx,-this.dy);
//用新的變形矩陣重繪
this.paint();
//繪制基準點
this.ctx.fillStyle="red";
this.ctx.fillRect(this.dx-5,this.dy-5,10,10);
//恢復狀態
this.ctx.restore();
}


var trans = new Transform();

//==========================================
function Clip(){
var canvas = document.getElementById("canvas3");
this.ctx = canvas.getContext("2d");
this.img=new Image();
this.img.src=IMG_SRC;
//移動方向
this.delta=[3,3];
//起始點
this.pos_x = 225;
this.pos_y = 120;
//半徑
this.radius = 40;
//畫布的長和寬
this.w = parseInt(canvas.getAttribute("width"));
this.h = parseInt(canvas.getAttribute("height"));
}

Clip.prototype.draw1
=function(){
//碰撞檢測
if (this.pos_x < this.radius) {
this.delta[0] = Math.random() % 4 + 5;
}
else if (this.pos_x > this.w - this.radius) {
this.delta[0] = -(Math.random() % 4 + 5);
}

if (this.pos_y < this.radius) {
this.delta[1] = Math.random() % 4 + 5;
}
else if (this.pos_y > this.h - this.radius) {
this.delta[1] = -(Math.random() % 4 + 5);
}

this.pos_x += this.delta[0];
this.pos_y += this.delta[1];

this.ctx.clearRect(0, 0, this.w, this.h);
//保存狀態
this.ctx.save()
//移動變形
this.ctx.translate(this.pos_x,this.pos_y);
//設置裁剪區域
this.ctx.beginPath();
this.ctx.arc(0 ,0,this.radius,0,Math.PI*2,true);
this.ctx.clip();
// 將圖片畫到畫布上
this.ctx.drawImage(this.img, -this.pos_x, -this.pos_y,this.w, this.h);
//恢復狀態
this.ctx.restore();
}

Clip.prototype.draw2
=function(){
//碰撞檢測
if (this.pos_x < this.radius) {
this.delta[0] = Math.random() % 4 + 5;
}
else if (this.pos_x > this.w - this.radius) {
this.delta[0] = -(Math.random() % 4 + 5);
}

if (this.pos_y < this.radius) {
this.delta[1] = Math.random() % 4 + 5;
}
else if (this.pos_y > this.h - this.radius) {
this.delta[1] = -(Math.random() % 4 + 5);
}

this.pos_x += this.delta[0];
this.pos_y += this.delta[1];

this.ctx.clearRect(0, 0, this.w, this.h);
//繪制灰色的半透明蒙版
this.ctx.fillStyle="rgba(125,125,125,0.9)"
this.ctx.fillRect(0, 0, this.w, this.h);
//保存狀態
this.ctx.save()
//移動坐標
this.ctx.translate(this.pos_x,this.pos_y);
//裁剪透明的圓形區域
this.ctx.globalCompositeOperation = "xor";
this.ctx.fillStyle="white"
this.ctx.beginPath();
this.ctx.arc(0 ,0,this.radius,0,Math.PI*2,true);
this.ctx.fill();
// 將圖片畫到蒙版的下面,即只露出透明區域
this.ctx.globalCompositeOperation = "destination-over";
this.ctx.drawImage(this.img, -this.pos_x, -this.pos_y,this.w, this.h);
//恢復狀態
this.ctx.restore();
}


var cl=new Clip();
cl.interval
=null;

function move(id){
if(cl.interval)
clearInterval(cl.interval)

if(id==1){
cl.ctx.clearRect(
0, 0, 450, 300);
cl.interval
=setInterval(function(){cl.draw1()},20);
}

else{
cl.ctx.clearRect(
0, 0, 450, 300);
cl.interval
=setInterval(function(){cl.draw2()},20);
}
}


function stop(){
clearInterval(cl.interval)
}


var compositeTypes = [
'source-over','source-in','source-out','source-atop',
'destination-over','destination-in','destination-out','destination-atop',
'lighter','darker','copy','xor'
];
function drawComp(){
for (i=0;i<compositeTypes.length;i++){
var label = document.createTextNode(compositeTypes[i]);
document.getElementById(
'lab'+i).appendChild(label);
var ctx = document.getElementById('tut'+i).getContext('2d');

// draw rectangle
ctx.fillStyle = "#09f";
ctx.fillRect(
15,15,70,70);

// set composite property
ctx.globalCompositeOperation = compositeTypes[i];

// draw circle
ctx.fillStyle = "#f30";
ctx.beginPath();
ctx.arc(
75,75,35,0,Math.PI*2,true);
ctx.fill();
}
}
drawComp();

</script>
0
0
 
標簽:HTML5
 
 

文章列表

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()