新聞中心
好吧,新的一天來(lái)了,我才開始動(dòng)筆,真夠懶得:)昨天說(shuō)了今天我們要畫一個(gè)球,在canvas上。好吧,這是游戲的入門的第一步,只是昨天沒寫完,所以。。。

成都創(chuàng)新互聯(lián)公司是一家以網(wǎng)絡(luò)技術(shù)公司,為中小企業(yè)提供網(wǎng)站維護(hù)、做網(wǎng)站、成都做網(wǎng)站、網(wǎng)站備案、服務(wù)器租用、域名注冊(cè)、軟件開發(fā)、微信小程序等企業(yè)互聯(lián)網(wǎng)相關(guān)業(yè)務(wù),是一家有著豐富的互聯(lián)網(wǎng)運(yùn)營(yíng)推廣經(jīng)驗(yàn)的科技公司,有著多年的網(wǎng)站建站經(jīng)驗(yàn),致力于幫助中小企業(yè)在互聯(lián)網(wǎng)讓打出自已的品牌和口碑,讓企業(yè)在互聯(lián)網(wǎng)上打開一個(gè)面向全國(guó)乃至全球的業(yè)務(wù)窗口:建站咨詢電話:13518219792
上面的代碼是在VS11 beta上寫的,實(shí)在是太舒服了,vs是非常強(qiáng)大的編輯器。上面的代碼中我們繪制了一個(gè)大大的圓,并且著色了,紅邊和黃心。
看下 arc (弧度)方法,昨天的文章里有他的鏈接地址,我在這里粘貼下。
The arc(x, y, radius, startAngle, endAngle, anticlockwise) method draws an arc.
arc(x,y,弧度,開始角度點(diǎn),結(jié)束角度點(diǎn), 順時(shí)針),角度點(diǎn)你可能不是很清楚如何表示,這里是用Math.PI 圓周率來(lái)表示 6.28是周長(zhǎng)。 想畫圓的一部分也就是一段弧線,可以取開始的角度點(diǎn)和結(jié)束的角度點(diǎn)。
那么下一步就是要把圓能夠畫到我們棋盤上。其實(shí),這個(gè)很簡(jiǎn)單,只要我們把x,y和radius的值調(diào)整下就會(huì)繪制出來(lái)。我把昨天代碼寫的更“專業(yè)”了一點(diǎn)。所以,今天的代碼會(huì)在新的代碼基礎(chǔ)上增加了。先看下改動(dòng)過(guò)的代碼。
- 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();
是吧,更專業(yè)了吧,這樣就不會(huì)定義一坨的function,到時(shí)候沒出找,而是定義在一個(gè)對(duì)象里,這種封裝也能避免命名沖突。而且,棋盤起始的位置我也做了調(diào)整,只要修改起始的x y值,棋盤就會(huì)在這個(gè)點(diǎn)開始畫。那,現(xiàn)在我們要在第五行,第六列畫一個(gè)黃色的球,該怎么畫呢?只需要給map增加一個(gè)方法,再調(diào)用這個(gè)方法就行啦
- 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();
- },
畫出來(lái)刷新下,居然是第六行,第五列,我們搞錯(cuò)了嗎?代碼沒有,只是我們誤認(rèn)為x是行y是列 按順序叫順口了,其實(shí)是反過(guò)來(lái)的:)
泡泡既然能畫出來(lái),也要能清除才是,不然沒法玩,所以再增加一個(gè)清除泡泡的方法。
- 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 哈哈,不過(guò)在獲取泡泡的位置時(shí)是不是很糾結(jié),為什么畫泡泡是 width/2 而擦除要加0.5?
畫圓是從中心點(diǎn)開始畫,所以要去掉半徑,而擦數(shù)不能擦掉我們的棋盤線,所以要偏移0.5 。
當(dāng)前題目:HTML 5游戲制作之五彩連珠(畫圖)
文章地址:http://m.fisionsoft.com.cn/article/coocjpd.html


咨詢
建站咨詢
