首页 > 代码库 > canvas一周一练 -- canvas绘制马尾图案 (5)

canvas一周一练 -- canvas绘制马尾图案 (5)

运行效果:

技术分享

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <canvas id="drawing" width="1000" height="600">A drawing of someing!</canvas>
    <script type="text/javascript">
     var drawing = document.getElementById(drawing);
        if(drawing.getContext) {
            //绘制马尾图案
            var context = drawing.getContext(2d);
            //随机颜色
            var addZero = function(str){
                return str.length === 2 ? str : 0+str;
            };
            var randomColor = function(redValue, greenValue, blueValue){
                redValue = addZero(redValue.toString(16));
                greenValue = addZero(greenValue.toString(16));
                blueValue = addZero(blueValue.toString(16));
                return # + redValue + greenValue + blueValue;
            };

            context.translate(250, 100);

            for(var i=0; i<50; i++) {
                context.fillStyle = randomColor(parseInt(Math.random()*256), parseInt(Math.random()*256), parseInt(Math.random()*256));
                context.scale(0.93, 0.93);//缩放
                context.rotate(Math.PI/9);//旋转画布
                context.translate(35, 12);
                context.fillRect(0, 0, 100, 50);
            }
        }

    </script>
</body>
</html>

 

canvas一周一练 -- canvas绘制马尾图案 (5)