十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團隊
量身定制 + 運營維護+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
今天就跟大家聊聊有關(guān)利用javascript怎么實現(xiàn)一個生成隨機圖形功能,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

第一步
在HTML和CSS中創(chuàng)建出現(xiàn)圖形的矩形和兩個按鈕。第一個按鈕用來產(chǎn)生圖形,第二個按鈕用來清除產(chǎn)生的所有圖形。
第二步
在javascript中分別創(chuàng)建用來隨機顏色的函數(shù),點擊隨機產(chǎn)生圖形的函數(shù),點擊清除屏幕的函數(shù)。
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
var btn=document.getElementById("btn");
var cle=document.getElementById("cle");設(shè)置圖形的隨機顏色
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;
}設(shè)置點擊按鈕隨機產(chǎn)生圖形的函數(shù),第一種實心和空心矩形,第二種實心和空心圓,第三種直線,它們的位置和大小分別寫隨機函數(shù),再分別加上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,recty,rectwidth,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,0,2*Math.PI,false);
context.stroke();
context.closePath();
}
else{
context.beginPath();
context.fillStyle=color();
context.arc(arcx,arcy,arcr,0,2*Math.PI,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();
}
}第三步
最后創(chuàng)建點擊清除屏幕的按鈕函數(shù),根據(jù)創(chuàng)建的屏幕大小,在canvas中添加 context.clearRect(0,0,600,600);可實現(xiàn)清除屏幕。
cle.onclick=function(){
context.beginPath();
context.clearRect(0,0,600,600);
context.closePath();
}看完上述內(nèi)容,你們對利用javascript怎么實現(xiàn)一個生成隨機圖形功能有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。