這周有點迷茫,不知道幹嗎了,一每天就過去了!我在博客右側公告欄加了qq交流,各位有好的主題,或者有趣的技術,歡迎交流!今天突發奇想,就寫了2個h5 canvas的demo玩玩!html
捨不得買2塊錢的刮刮樂,就只能寫個相似的功能過過彩票癮了!前端
<div id="lottery" style="width:300px;height:500px;margin:10px;border-radius:5px;float:left;"> <div style="width:300px;height:100px;line-height:100px;text-align:center;font-size:33px;color:blueviolet;">NICK彩票</div> <div id="txt" style="width:300px;height:200px;font-size:40px;color:peachpuff;display:flex;justify-content:center;align-items:center;flex-direction:column;"> <span>祝</span> <span>君</span> <span>中</span> <span>獎</span> </div> <div id="canvasArea" style="width:300px;height:200px;position:relative;"> <div style="width:300px;height:200px;position:absolute;top:0;left:0;z-index:1;text-align:center;line-height:200px;font-weight:bold;font-size:56px;color:indianred;">一等獎</div> <canvas id="canvas" width="300px" height="200px" style="position:absolute;top:0;left:0;z-index:2;"></canvas> </div> </div>
這段html要注意的地方有2個:canvas
var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d");
context.fillStyle='#A9AB9D'; context.fillRect(10,10,280,180); context.fillStyle='#000'; context.font='50px Arial'; context.fillText('刮獎區',75,115);
以上都是canvas基礎api,看w3c就ok了。api
setInterval(function(){ document.getElementById('txt').style.color = document.getElementById('txt').style.color=='peachpuff' ? 'yellow' : 'peachpuff'; },500);
var brush=function(){//刮獎 context.clearRect(event.offsetX,event.offsetY,20,20); };
canvas.onmousedown = function(){ // 鼠標按下時 - 綁定鼠標跟隨事件 bindHandler(canvas,'mousemove',brush,false); } canvas.onmouseup = function(){ // 中止刮獎功能 - 解綁鼠標跟隨事件 removeHandler(canvas,"mousemove",brush,false); }
這裏的事件綁定與解綁我上篇博文有封裝,最後完整代碼也有!app
刮刮樂happy到底結束!最後附上完整代碼,再看看效果吧!ide
<div style="width:300px;height:500px;margin:10px;border-radius:10px;overflow:hidden;float:right;"> <canvas id="canvas2" width="300px" height="500px" style=""></canvas> </div>
var canvas2 = document.getElementById("canvas2"); var context2 = canvas2.getContext("2d");
var draw=function(){ context2.fillRect(event.offsetX,event.offsetY,10,10); };
context2.font='20px Arial'; context2.strokeText('NICK畫筆',100,30);//寫個頭 //1. 爲canvas元素onmousedown和onmouseup事件 canvas2.onmousedown = function(){ // 啓用畫筆功能 - 綁定鼠標跟隨事件 bindHandler(canvas2,'mousemove',draw,false); } canvas2.onmouseup = function(){ // 中止畫筆功能 - 解綁鼠標跟隨事件 removeHandler(canvas2,"mousemove",draw,false); }
畫圖工具的畫筆功能到底結束!函數
附上完整代碼:工具
代碼寫完了,我也想說點其餘的:佈局
上面js代碼中,有很多註釋,我將其分爲幾個區域:插件方法封裝區、命名區、功能實現區、刮刮樂區以及畫筆區等,我感受這樣寫加上一些註釋,能使代碼能加簡潔,便於之後的維護!固然這只是我的觀點,歡迎各位點擊我博客右邊公告欄的qq交流交流!字體
最後附上:
上篇博文:事件綁定與解綁!(只是一個簡單的封裝)
來看看效果,玩玩吧!