js操作canvas实现点击拖动生成颜色方块矩形再次点击可移动方块示例代码

代码语言:html

所属分类:拖放

代码描述:js操作canvas实现点击拖动生成颜色方块矩形再次点击可移动方块示例代码维五子棋围棋黑白棋子排列落子动画效果代码,点击可实现三维空间旋转。

代码标签: js 操作 canvas 点击 拖动 生成 颜色 方块 矩形 再次 点击 可移动 方块

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Canvas拖动方块</title>
</head>

<body>

    <canvas id="canvas" width="500" height="500" style="border:1px solid red;"></canvas>

    <script>
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        
        let startX, startY; 
        let isDrawing = false;
     
        const rects = [];
        
      
        let selectedSquare = null;
            let offsetX, offsetY;
    
      function findSquare(x, y) {
          
         
                for (let i = rects.length - 1; i >= 0; i--) {
                    const square = rects[i];
                    if (x >= square.x && x <= square.x + square.w &&
                        y >= square.y && y <= square.y + square.h) {
                        return square;
                    }
                }
                return null;
            }
        
        canvas.addEventListener('mousedown', (e) => {
             const mouseX = e.clientX - canvas.getBoundingClientRect().left;
                const mouseY = e.clientY - canvas.getBoundingClientRect().top;
                selectedSquare = findSquare(mouseX, mouseY);
                if (selectedSquare) {
                       console.log("drag start");
                    offsetX = mouseX - selectedSquare.x;
                    offsetY = mouseY - selectedSquare.y;
                }else{
                      startX = e.offsetX;
                      startY = e.offsetY;
                      isDrawing = true;
                }
    
     
    .........完整代码请登录后点击上方下载按钮下载查看

网友评论0