canvas实现滚动条缩放图片的demo

哈沛
2023-12-01
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body style="background: black;">
    <canvas id="myCanvas" style="display: block;border: 10px solid #aaa;margin: 0 auto;">
        你的浏览器不支持canvas
    </canvas>
    <input type="range" id="scale_range" min="0.5" max="3.0" value="1.0" step="0.01" style="display: block;margin: 20px auto;width: 800px;">

<script>
    var myCanvas = document.getElementById("myCanvas");
    var context = myCanvas.getContext("2d");
    var slider = document.getElementById("scale_range");
    var image = new Image();

    window.onload = function (){

        myCanvas.width = 300;
        myCanvas.height = 200;

        var scale = slider.value;

        image.src = '1.jpg';

        image.onload = function () {

           // context.drawImage(image,750,750,200,200,0,0,800,800);
            drawImageByScale(scale);
            slider.onmousemove = function () {
                scale = slider.value;
                drawImageByScale(scale);
            }

        }
function drawImageByScale(scale) {
    var imageWidth = 300*scale;
    var imageHeight = 200*scale;

   // var sx = imageWidth / 2 - myCanvas.width / 2;
    //var sy = imageHeight /2 - myCanvas.height / 2;

    var dx = myCanvas.width / 2 - imageWidth / 2;
    var dy = myCanvas.height /2 - imageHeight / 2;

    context.clearRect(0,0,myCanvas.width,myCanvas.height);
    context.drawImage(image,dx,dy,imageWidth,imageHeight);

   // context.drawImage(image,sx,sy,myCanvas.width,myCanvas.height,0,0,myCanvas.width,myCanvas.height);
}

    }
</script>
</body>
</html>
 类似资料: