codeing or artist ?
记得大学第一节编程课,教授说,"如果一件事儿有对错,那么是科学。如果有美丑好坏,那么是艺术。" 一个能顺利运行还能让人阅读时体验思维美妙的代码,就是艺术和科学的结合。能运行的程序并不是好程序,能当作文章来读的才是。在我看来代码是一种特殊的文体,程序猿其实会写诗。

不啰嗦上代码:

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

 

posted on 2016-08-29 17:02  codeing-or-artist-??  阅读(1350)  评论(0编辑  收藏  举报