码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-08-29 17:43:05      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

不啰嗦上代码:

<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>

 

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

标签:

原文地址:http://www.cnblogs.com/gongshunkai/p/5818709.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!