• 实现鼠标拖动canvas绘制的图片


    不啰嗦上代码:

    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>无标题文档</title>
    </head>
    
    <body>
    <canvas id="gameCanvas" width="500px" height="300px"></canvas>
    <script>
    var cvs = document.getElementById('gameCanvas');
    var ctx = cvs.getContext('2d');
    //绘制黑色背景
    ctx.fillStyle = 'black';
    ctx.fillRect(0, 0, 500,300);
    //绘制红色矩形
    ctx.fillStyle = 'red';
    ctx.fillRect(100, 100, 100,100);
    //记录矩形的位置
    var posX = 100;
    var posY = 100;
            
    cvs.onmousedown = function(e){
    
        var x = e.clientX - posX;
        var y = e.clientY - posY;
    
        //判断鼠标是否点击在矩形内
        if(e.clientX >= posX + this.offsetLeft && e.clientX <= posX + 100 + this.offsetLeft && e.clientY >= posY + this.offsetTop && e.clientY <= posY + 100 + this.offsetTop){
        
            document.onmousemove = function(e){
                //ctx.clearRect(posX, posY, 100,100);
                
                //鼠标拖动时重绘黑色背景
                ctx.fillStyle = 'black';
                ctx.fillRect(0, 0, 500,300);
                //鼠标拖动时重绘红色矩形
                ctx.fillStyle = 'red';    
                ctx.fillRect(e.clientX-x, e.clientY-y, 100,100);
                //记录矩形的位置
                posX = e.clientX-x;
                posY = e.clientY-y;
            };
            document.onmouseup = function(){
                document.onmousemove = null;
            };
        }
    };
    </script>
    </body>
    </html>
  • 相关阅读:
    Contest (树状数组求逆序对)
    树状数组
    unity3D 笔记 (NENE QUEST 制作中用到的函数)
    Ubuntu 安装gnome桌面及vnc远程连接
    Pillow图像处理
    室内场景数据集
    PyTorch踩坑笔记
    进一步了解pip
    一些概念
    损失函数及评价指标
  • 原文地址:https://www.cnblogs.com/gongshunkai/p/5818709.html
Copyright © 2020-2023  润新知