使用按钮做图片缩放

使用 Canvas 显示图片,通过放大(zoom in)、缩小(zoom out)、重置(reset)按钮来修改图片的显示效果。

基于以下教程开发

1.添加 button 按钮

<div style="float: right">
  <button class="zoomButton" onclick="zoomOut()">Zoom Out</button>
  <button class="zoomButton" onclick="zoomIn()">Zoom In</button>
  <button class="zoomButton" onclick="resetZoomLevel()">Reset</button>
</div>

2.在渲染图片时加入缩放比例 zoomRate

// 全局变量zoomRate
let zoomRate = 1

function drawImage(){
    const canvasContainer = document.getElementById("canvasContainer");
    const canvas = document.getElementById("canvas");
    const context = canvas.getContext("2d");

    if (canvasContainer && canvas) {
        if (context) {
            const img = new Image();
            img.src = imageData; // 图片base64后的string
            img.onload = () => {
            // 计算图片的缩放比例
            // 使用原尺寸高度,在默认状态下会出现上下滚动条
            const heightScaleRate =
                (canvasContainer.offsetHeight - 5) / img.height;
            const widthScaleRate =
                (canvasContainer.offsetWidth - 5) / img.width;
            // 选取比率小的,以防超过边界出现滚动条
            const scaleRate =
                heightScaleRate > widthScaleRate
                ? widthScaleRate
                : heightScaleRate;
            context.scale(scaleRate, scaleRate);

            canvas.width = Math.round(
                img.width * scaleRate * zoomRate
            );
            canvas.height = Math.round(
                img.height * scaleRate * zoomRate
            );

            context.beginPath();
            context.drawImage(
                img,
                0,
                0,
                canvas.width,
                canvas.height
            );
            context.stroke();
            };
        }
    }
}


























 
 
 
 
 
 














3.添加 button 的点击事件

zoomIn() {
    zoomRate = zoomRate * 1.1;
    drawImage();
    document.getElementsByClassName("zoomButton")[1].blur();
}

zoomOut() {
    zoomRate = zoomRate / 1.1;
    drawImage();
    document.getElementsByClassName("zoomButton")[0].blur();
}

resetZoomLevel() {
    zoomRate = 1;
    imageData = originImageData; // originImageData是图片的原始数据,未缩放时imageData等于originImageData
    drawImage();
    document.getElementsByClassName("zoomButton")[2].blur();
}

可通过按钮、框选、滚轮滚动来放大缩小图片的示例:

Sorry, your browser does not support HTML5 Canvas functionality which is required for this application.