汤小殇

canvas初体验

利用画布,绘制随机大小,颜色,位置 方框
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>H5-canvas</title> <style type="text/css"> canvas{background: #f1aaa3; margin: 80px auto; display: block;} </style> </head> <body > <canvas id="canvas" width="900px" height="468px"> </canvas> </body> <script type="text/javascript"> var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); var width = canvas.width; var height = canvas.height; // context.fillStyle = "#008ce1"; //填充色 // context.strokeStyle = "#515151"; //描边色 // context.globalAlpha = 0.5; // 透明度 // context.fillRect(10,20,100,100); //x,y,w,h 方形 // context.strokeRect(10,150,88,88); //描边 // context.clearRect(20,30,50,50); //橡皮擦 //随机颜色函数 function randomColor(){ var r = Math.floor(Math.random()*256); var g = Math.floor(Math.random()*256); var b = Math.floor(Math.random()*256); var color = 'rgb('+r+','+g+','+b+')'; console.log(color); return color; } //canvas内随机位置大小方框函数 function randomSize(){ var x = Math.random()*width; var y = Math.random()*height; var w = Math.random()*(width-x); var h = Math.random()*(height-y); var data = [x,y,w,h]; console.log(data); return data; } //canvas内随机位置出现随机大小颜色方框 function randomRect(){ context.strokeStyle = randomColor(); var data = randomSize(); context.strokeRect(data[0],data[1],data[2],data[3]); //递归每隔0.5秒执行一次当前函数 setTimeout(randomRect,500); } randomRect(); </script> </html>

 

posted on 2017-03-16 20:14  汤小殇  阅读(100)  评论(0编辑  收藏  举报

导航