<!DOCTYPE html>
<html>
<head>
<title>Canvas 拖拽和等比例缩放</title>
<style>
canvas {
    border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
// 获取 canvas 元素和绘图上下文
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

// 矩形的初始位置和大小
var rect = {
    x: 100,
    y: 100,
    width: 100,
    height: 100
};

// 记录鼠标当前位置和矩形的初始位置
var mouseX, mouseY;
var startX, startY;

// 监听鼠标按下事件
canvas.addEventListener('mousedown', function (e) {
    mouseX = e.pageX - canvas.offsetLeft;
    mouseY = e.pageY - canvas.offsetTop;

    // 判断鼠标是否在矩形内部
    if (mouseX > rect.x && mouseX < rect.x + rect.width && mouseY > rect.y && mouseY < rect.y + rect.height) {
        startX = rect.x;
        startY = rect.y;

        // 监听鼠标移动事件
        canvas.addEventListener('mousemove', dragRect);
    }
});

// 监听鼠标松开事件
canvas.addEventListener('mouseup', function () {
    // 停止监听鼠标移动事件
    canvas.removeEventListener('mousemove', dragRect);
});

// 监听按键按下事件
document.addEventListener('keydown', function (e) {
    // 判断是否按下 Shift 键
    if (e.shiftKey) {
        // 监听鼠标移动事件
        canvas.addEventListener('mousemove', scaleRect);
    }
});

// 监听按键松开事件
document.addEventListener('keyup', function () {
    // 停止监听鼠标移动事件
    canvas.removeEventListener('mousemove', scaleRect);
});

// 拖拽矩形
function dragRect(e) {
    var moveX = e.pageX - canvas.offsetLeft - mouseX;
    var moveY = e.pageY - canvas.offsetTop - mouseY;

    rect.x = startX + moveX;
    rect.y = startY + moveY;

    drawRect();
}

// 等比例缩放矩形
function scaleRect(e) {
    var moveX = e.pageX - canvas.offsetLeft - mouseX;
    var moveY = e.pageY - canvas.offsetTop - mouseY;

    // 判断鼠标移动的方向
    if (moveX > moveY) {
        rect.width = rect.height + moveY;
    } else {
        rect.height = rect.width + moveX;
    }

    drawRect();
}

// 绘制矩形
function drawRect() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillRect(rect.x, rect.y, rect.width, rect.height);
}

// 初始化绘制
drawRect();
</script>
</body>
</html>
JavaScript Canvas 矩形拖拽和按住 Shift 等比例缩放

原文地址: https://www.cveoy.top/t/topic/pSsE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录