javascript實現點選產生隨機圖形
阿新 • • 發佈:2021-01-27
本文例項為大家分享了javascript實現點選產生隨機圖形的具體程式碼,供大家參考,具體內容如下
點選產生隨機圖形
效果如下:
用javascript來實現
主要用canvas和隨機函式完成各種圖形
第一步
在HTML和CSS中創建出現圖形的矩形和兩個按鈕。第一個按鈕用來產生圖形,第二個按鈕用來清除產生的所有圖形。
<style> *{ margin: 0; padding: 0; } #canvas{ border: solid 1px red; display: block; margin: 0 auto; } #father{ width: 200px; margin:0 auto; } #btn{ margin-right: 40px; cursor: pointer; } #cle{ cursor: pointer; } </style>
<body> <canvas id="canvas" width="600" height="600"></canvas> <div id="father"> <input type="button" id="btn" value="點選生成"> <input type="button" id="cle" value="點選清除"> </div> </body>
第二步
在javascript中分別建立用來隨機顏色的函式,點選隨機產生圖形的函式,點選清除螢幕的函式。
var canvas=document.getElementById("canvas"); var context=canvas.getContext("2d"); var btn=document.getElementById("btn"); var cle=document.getElementById("cle");
設定圖形的隨機顏色
function color(){ var r=Math.floor(Math.random()*255); var g=Math.floor(Math.random()*255); var b=Math.floor(Math.random()*255); var a=Math.random(); var bg="rgba("+r+","+g+","+b+","+a+")"; return bg; }
設定點選按鈕隨機產生圖形的函式,第一種實心和空心矩形,第二種實心和空心圓,第三種直線,它們的位置和大小分別寫隨機函式,再分別加上canvas程式碼,用來畫圖形,如context.beginPath()-context closePath()。
btn.onclick=function(){ var random=Math.floor(Math.random()*3+1); if(random==1){ var rectr=Math.floor(Math.random()*2); var rectx=Math.floor(Math.random()*600); var recty=Math.floor(Math.random()*600); var rectwidth=Math.floor(Math.random()*200+200); var rectheight=Math.floor(Math.random()*200+200); if(rectr== 0){ context.beginPath(); context.strokeStyle=color(); context.strokeRect(rectx,recty,rectwidth,rectheight) context.closePath(); } else { context.beginPath(); context.fillStyle=color(); context.fillRect(rectx,rectheight); context.closePath(); } } else if(random == 2){ var arcr=Math.floor(Math.random()*2); var arcx=Math.floor(Math.random()*600); var arcy=Math.floor(Math.random()*600); var arcr=Math.floor(Math.random()*300); if(arcr==0){ context.beginPath(); context.strokeStyle=color(); context.arc(arcx,arcy,arcr,2*Math.PI,false); context.stroke(); context.closePath(); } else{ context.beginPath(); context.fillStyle=color(); context.arc(arcx,false); context.fill(); context.closePath(); } } else if(random==3){ var movex=Math.floor(Math.random()*600); var movey=Math.floor(Math.random()*600); var linex=Math.floor(Math.random()*600); var liney=Math.floor(Math.random()*600); var linew=Math.floor(Math.random()*20); context.beginPath(); context.strokeStyle=color(); context.moveTo(movex,movey); context.lineTo(linex,liney); context.lineWidth=linew; context.stroke(); context.closePath(); } }
第三步
最後建立點選清除螢幕的按鈕函式,根據建立的螢幕大小,在canvas中新增 context.clearRect(0,600,600);可實現清除螢幕。
cle.onclick=function(){ context.beginPath(); context.clearRect(0,600); context.closePath(); }
點選產生隨機圖形的效果完成了!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。