当前位置: 首页 > 工具软件 > Meta2d.js > 使用案例 >

HTML5 Canvas ( 扩展context('2d') ) CanvasRenderingContext2D.prototype.你的方法名

西门良才
2023-12-01
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>canvas</title>
    <script type="text/javascript" src="../js/jQuery.js"></script>
    <style type="text/css">
        *{
            margin: 0;
            padding: 0;
            outline: none;
            border: none;
        }
        #canvas{
            margin: auto auto;
            width: 7rem;
            margin: .25rem 0 0 1.5rem;
            border: 1px solid black;
        }
    </style>
</head>
<body> 
    <canvas id="canvas" width="1000" height="600"></canvas>
</body>
</html>
<script type="text/javascript">
    /**
     * rem 布局初始化
     */
    $('html').css('font-size', $(window).width()/10);
    /**
     * 获取 canvas 画布
     * 获取 canvas 绘图上下文环境
     */
    var canvas = $('#canvas')[0];
    var cxt = canvas.getContext('2d');
    
    /**
     * 扩展context('2d'), 绘制五角星的方法
     */
    CanvasRenderingContext2D.prototype.fillFiveStar = function(fiveStar){
        this.beginPath();
        this.lineWidth = 10;
        var x = 0, y = 0;
        for(var i = 0; i < 5; i++){
            x = Math.cos((18+72*i-fiveStar.RotationAngle)/180*Math.PI);
            x = x*fiveStart.bigRadius+fiveStar.offsetX;
            y = -Math.sin((18+72*i-fiveStar.RotationAngle)/180*Math.PI);
            y = y*fiveStart.bigRadius+fiveStar.offsetY;
            this.lineTo(x,y);
            x = Math.cos((54+i*72-fiveStar.RotationAngle)/180*Math.PI);
            x = x*fiveStart.smallRadius+fiveStar.offsetX;
            y = -Math.sin((54+i*72-fiveStar.RotationAngle)/180*Math.PI);
            y = y*fiveStart.smallRadius+fiveStar.offsetY;
            this.lineTo(x,y);
        }
        this.closePath();
        this.stroke();
    }
    
    /**
     * 调用扩展的方法
     */
    var fiveStart = {
        bigRadius: 200,
        smallRadius: 30,
        offsetX: 400,
        offsetY: 300,
        RotationAngle: 0
    }
    cxt.fillFiveStar(fiveStart);
</script>

 

 类似资料: