HTML 5游戲制作之五彩連珠(畫圖)
好吧,新的一天來了,我才開始動筆,真夠懶得:)昨天說了今天我們要畫一個球,在canvas上。好吧,這是游戲的入門的第一步,只是昨天沒寫完,所以。。。
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title></title>
- </head>
- <body>
- <canvas id="canvas" height="400" width="600" style="background: #fff;"></canvas>
- <script type="text/javascript">
- var canvas = document.getElementById("canvas");
- var ctx = canvas.getContext("2d");
- ctx.beginPath();
- ctx.arc(110, 110, 40, 0, Math.PI * 2);
- ctx.strokeStyle = "red";
- ctx.fillStyle = "yellow";
- ctx.fill();
- ctx.stroke();
- </script>
- </body>
- </html>
上面的代碼是在VS11 beta上寫的,實在是太舒服了,vs是非常強大的編輯器。上面的代碼中我們繪制了一個大大的圓,并且著色了,紅邊和黃心。
看下 arc (弧度)方法,昨天的文章里有他的鏈接地址,我在這里粘貼下。
The arc(x, y, radius, startAngle, endAngle, anticlockwise) method draws an arc.
arc(x,y,弧度,開始角度點,結束角度點, 順時針),角度點你可能不是很清楚如何表示,這里是用Math.PI 圓周率來表示 6.28是周長。 想畫圓的一部分也就是一段弧線,可以取開始的角度點和結束的角度點。
那么下一步就是要把圓能夠畫到我們棋盤上。其實,這個很簡單,只要我們把x,y和radius的值調整下就會繪制出來。我把昨天代碼寫的更“專業”了一點。所以,今天的代碼會在新的代碼基礎上增加了。先看下改動過的代碼。
- var canvas = document.getElementById("canvas");
- var ctx = canvas.getContext("2d");
- var g = {
- cellCount: 9,
- lineCount: 5,
- };
- var map = {
- startX: 20.5,
- startY: 60.5,
- cellWidth: 30,
- getEndX: function () {
- return g.cellCount * this.cellWidth + this.startX;
- },
- getEndY: function () {
- return g.cellCount * this.cellWidth + this.startY;
- },
- draw: function () {
- ctx.beginPath();
- ctx.moveTo(this.startX, this.startY);
- for (var i = 0; i <= g.cellCount; i++) {
- var p1 = i * this.cellWidth + this.startX;
- ctx.moveTo(p1, this.startY);
- ctx.lineTo(p1, this.getEndY());
- var p2 = i * this.cellWidth + this.startY;
- ctx.moveTo(this.startX, p2);
- ctx.lineTo(this.getEndX(), p2);
- }
- ctx.strokeStyle = "#456";
- ctx.stroke();
- },
- };
- map.draw();
是吧,更專業了吧,這樣就不會定義一坨的function,到時候沒出找,而是定義在一個對象里,這種封裝也能避免命名沖突。而且,棋盤起始的位置我也做了調整,只要修改起始的x y值,棋盤就會在這個點開始畫。那,現在我們要在第五行,第六列畫一個黃色的球,該怎么畫呢?只需要給map增加一個方法,再調用這個方法就行啦
- drawBubble: function (x, y) {
- var px = this.startX + this.cellWidth * x - this.cellWidth / 2;
- var py = this.startY + this.cellWidth * y - this.cellWidth / 2;
- ctx.beginPath();
- ctx.arc(px, py, 12, 0, Math.PI * 2);
- ctx.strokeStyle = "white";
- ctx.fillStyle = "yellow";
- ctx.fill();
- ctx.stroke();
- },
畫出來刷新下,居然是第六行,第五列,我們搞錯了嗎?代碼沒有,只是我們誤認為x是行y是列 按順序叫順口了,其實是反過來的:)
泡泡既然能畫出來,也要能清除才是,不然沒法玩,所以再增加一個清除泡泡的方法。
- clearBubble: function (x, y) {
- var px = this.startX + this.cellWidth * x - this.cellWidth + 0.5;
- var py = this.startY + this.cellWidth * y - this.cellWidth + 0.5;
- ctx.beginPath();
- ctx.clearRect(px, py, this.cellWidth - 1, this.cellWidth - 1);
- ctx.stroke();
- }
ok,是不是很霸氣? o(∩_∩)o 哈哈,不過在獲取泡泡的位置時是不是很糾結,為什么畫泡泡是 width/2 而擦除要加0.5?
畫圓是從中心點開始畫,所以要去掉半徑,而擦數不能擦掉我們的棋盤線,所以要偏移0.5 。
原文鏈接:http://www.cnblogs.com/mad/archive/2012/03/11/2390281.html
【編輯推薦】