HTML5 responsive canvas: resizing the browser canvas draw disappear

后端 未结 7 1632
一向
一向 2020-12-03 02:29

I want to make a responsive canvas using size in percentage and once user will resize the window the canvas adjust relatively. I am able to scale the canvas by using below c

相关标签:
7条回答
  • 2020-12-03 02:48

    Thanks. it was really helpful. below is the code what i was trying to do.

    #main{
    display:block;
    width:80%;
    height:300px;
    background:#e0e0e0;
    } 
    canvas{display:block;background:#fff;border:1px solid red;}
    
    </style>
    
    <script>
    
    $(function(){
    
    var container=document.getElementById("main");
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    
    // draw some content
    //alert(canvas.width);
    
    var w=$(container).width();
    var h=$(container).height();
    
    
    
    $(window).resize( saveResizeAndRedisplay );
    function saveResizeAndRedisplay(){
    
        // save the canvas content as imageURL
        var data=canvas.toDataURL();
    
        // resize the canvas
        canvas.width = $(container).width();
        canvas.height = $(container).height();
        //alert($(container).width());
    
        // scale and redraw the canvas content
        var img=new Image();
        img.onload=function(){
            ctx.drawImage(img,0,0,img.width,img.height);
        }
        img.src=data;
    
    }
    
    saveResizeAndRedisplay();
    
    }); 
    </script>
    
    </head>
    
    <body>
    
    <div id="main" role="main">
     <canvas id="canvas" width=200 height=150></canvas>
    </div>
    
    <script>
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var x = null;
    var y;
    
    canvas.onmousedown = function(e){
    x = e.pageX - canvas.offsetLeft;
    y = e.pageY - canvas.offsetTop;
    ctx.beginPath();
    ctx.moveTo(x,y);
    }
    
    canvas.onmouseup = function(e){
    x=null;
    }
    
    
    canvas.onmousemove = function(e){
    if(x==null) return;
    x = e.pageX - canvas.offsetLeft;
    y = e.pageY - canvas.offsetTop; 
    ctx.lineTo(x,y);
    ctx.stroke();
    }
    </script>
    
    0 讨论(0)
提交回复
热议问题