zoukankan      html  css  js  c++  java
  • 实现鼠标拖动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>
  • 相关阅读:
    轻松记账方法(A)
    个人学习进度(第八周)
    个人学习进度(第八周)
    Web版四则运算
    个人学习进度(第七周)
    个人学习进度(第六周)
    数组的子数组和最大值
    个人学习进度(第五周)
    个人学习进度(第四周)
    个人学习进度(第三周)
  • 原文地址:https://www.cnblogs.com/gongshunkai/p/5818709.html
Copyright © 2011-2022 走看看