Canvas縮放圖像

<body>
<canvas id="canvas"></canvas>
<input type="range" id="scale_range" min="0.5" max="3" step="0.01" value="1.0">
<script>
    slider = document.getElementById("scale_range");
    canvas = document.getElementById("canvas");
    context = canvas.getContext("2d");
    var image = new Image();
    window.onload = function(){
        canvas.width = 500;
        canvas.height = 500;
        image.src = "/a.png";
        var scale = slider.value;
        image.onload = function(){
            drawByScale(scale);
            slider.onmousemove = function(){
                scale = slider.value;
                drawByScale(scale);
            }

        }
    }
    function drawByScale(scale){
        var imageWidth = canvas.width*scale;
        var imageHeight = canvas.height*scale;
        //var sx = imageWidth/2-canvas.width/2;
        //var sy = imageHeight/2-canvas.height/2;
        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>
發佈了66 篇原創文章 · 獲贊 17 · 訪問量 37萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章