美文网首页
图片的放大与缩小

图片的放大与缩小

作者: congcongnanian | 来源:发表于2017-07-25 17:08 被阅读0次

    用canvas的drawImage绘制图像

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>图片缩放</title>
    </head>
    <body style="background: #000;">
        <canvas id="canvas" style="display: block;margin:0 auto;background: #fff;"></canvas>
            <input type="range" name="" id="scale-canvas" min="0.5" max="3.0" value="1.0" step="0.01" style="display: block;width:300px;margin:0 auto;">
        <script type="text/javascript">
            var range = document.getElementById('scale-canvas');
            var canvas = document.getElementById('canvas');
            var context = canvas.getContext('2d');
            var image = new Image();
    
            window.onload = function(){
                canvas.width = 418;
                canvas.height =435;
                image.src = '2.jpg';
                var scale =  range.value;
    
                image.onload = function () {
    
                    drawImageByRange(scale);
                    range.onmousemove = function () {
                        scale = range.value;
                        drawImageByRange(scale);
                    }
                }
            }
    
    
            function drawImageByRange(scale){
                  var imageWidth = canvas.width * scale ;
                  var imageHeight = canvas.height * scale ;
    
                  var dx = canvas.width / 2 - imageWidth / 2;
                  var dy = canvas.height / 2 - imageHeight / 2;
    
                  context.clearRect( 0 , 0 ,canvas.width , canvas.height);
                  context.drawImage(image, dx , dy , imageWidth , imageHeight );
    
            }
        </script>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:图片的放大与缩小

          本文链接:https://www.haomeiwen.com/subject/mptgkxtx.html