原创

如何动态设置HTML5中canvas宽度和高度

1.直接上代码

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div id="cc" style="width:20%;height:20%;border:1px solid black;">
    </div>
<script>
    function x1(did){
        //初始化context
        var cobj = new initC(did,1);
        var context = cobj.c;
        var w = cobj.w
        var h = cobj.h

        //开始画
        context.moveTo( 0 , 0 );
        context.lineTo(  300*w, 300*h );
        context.lineWidth = 1;
        context.strokeStyle = "red";
        context.stroke(); 

        context.beginPath();
        context.arc(230*w,100*h,50*w,0,2*Math.PI);
        context.stroke();  
    }

    //i
    function initC(did,lvwh){
        //宽高比
        if(!lvwh){
            lvwh = 1;
        }

        var oDiv=document.getElementById(did);
        oDiv.innerHTML = "";
        var canvas = document.createElement('canvas');
        oDiv.appendChild(canvas);
        document.body.appendChild(oDiv);

        var width = oDiv.clientWidth;
        // var height = oDiv.clientHeight;
        if(!width){
            width = oDiv.getAttribute("width");
            // height = oDiv.getAttribute("height");
        }

        var dw = width;
        var dh = width*lvwh;
        canvas.width = dw;
        canvas.height = dh;

        var w = dw/300;
        var h = dh/300*lvwh;
        var context = canvas.getContext("2d");
        return {c:context,w:w,h:h};
    }

    window.onload = function(){
        x1("cc");
        window.onresize = function(){
            x1("cc");
        }
    }
</script>
</body>
</html>

2.分析

  1. 在定义外层div的时候就设定好宽高,是百分比或者具体px都可以,下面会根据宽高比系数,计算宽高系数
  2. 生成宽高比返回对象 {c:context,w:w,h:h}
  3. 在实际绘画中宽高需要乘以对应的宽高比即可
  4. window.onresize 来监听浏览器窗口的大小变化,让canvas重绘达到动态改变宽高比效果

3.改进

  1. 其中lvwh宽高比系数可以根据div的宽高自动计算
正文到此结束
本文目录