Giter VIP home page Giter VIP logo

fakefish.github.com's People

Contributors

fakefish avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

fakefish.github.com's Issues

clone object in javascript

// this code below is copy from <Node.js开发指南> writen by byvoid

// shallow copy
Object.prototype.clone = function(){
  var newObj = {};
  for (var i in this) {
    newObj[i] = this[i];
  }
  return newObj;
}
// deep copy
Object.prototype.clone = function(){
  var newObj = {};
  for (var in in this) {
    if (typeof(this[i]) == 'object' || typeof(this[i] == 'function') {
      newObj[i] = this[i].clone();
    } else {
      newObj[i] = this[i];
    }
  }
  return newObj;
};

Array.prototype.clone = function(){
  var newArray = [];
  for (var i=0; i<this.length;i++){
    if (typeof(this[i] == 'object' || typeof(this[i]) == 'function') {
      newArray[i] = this[i].clone();
    } else {
      newArray[i] = this[i];
    }
  }
  return newArray;
};

Function.prototype.clone = function(){
  var that = this;
  var newFunc = function(){
    return that.apply(this, arguments);
  };
  for (var i in this) {
    newFunc[i] = this[i];
  }
  return newFunc;
};

var obj = {
  name : 'byvoid',
  likes : ['node'],
  display : function(){
    return this.name;
  }
};
var newObj = obj.clone();
newObj.likes.push('python');
obj.likes
>['node']
newObj.likes
>['node', 'python']
newObj.display == obj.display
>false

// this function is only cannot work like this
var obj1 = {rel : null};
var obj2 = {rel : obj1};
obj1.ref = obj2;

校招题目之多个数组取唯一值

function array_diff(){
  var arr,result,tab,index;
  result=[];
  tab=[{
    value:'',
    num:''
  }];
  for(var i=0,len=arguments.length;i<len;i++){
    arr = arguments[i];

    for(var j=0,l=arr.length;j<l;j++){
      index=-1;
      if(!isNaN(arr[j])){
        for(var x=0;x<tab.length;x++){
          if(arr[j]===tab[x].value){
            index=x;
          }
        }
        if(index==-1){
          tab.push({
            value:arr[j],
            num:1
          });

        }else{
          tab[index].num+=1;
        }

      }
    }
  }
  for(i=0,len=tab.length;i<len;i++){
    if(tab[i].num==1){
      result.push(tab[i].value);
    }
  }
  return result;
}
console.log(array_diff( [1, 2, 3, 'a'], [2, 3, 4, 'b'], [3, 4, 5, 'd']));

js和dom实现的贪吃蛇

额 月底的时候突然想写个贪吃蛇的游戏,然后大概花了一天的时间写完基本的玩法。然后在考虑一些自动的方法,先写了一个猥琐的方法,没有bug,但效率很低。想了bfs算法,但是js没有二维数组,感觉不太能完全实现。

所以想了这么一个方法:
蛇每走一步会计算头与得分点的位置。

建立一个二叉树,头为二叉树顶点,自动计算左右节点。
默认选择左节点,如果左节点在body中,那选择右节点。
如果右节点也不行的话,那么点在蛇身的圈子里。

所以感觉二叉树不能完全实现,本来蛇头是有3个方向,如果建立三叉树的话应该会更好点吧。

先mark,以后再写吧,这两天考虑算法有点头大了。

demo

code

嘛~以后有机会了看看A*算法,这个貌似能解决
pathfinding.js

html5资源加载

ResourceLoader.handleAudio = function(rsobj, callback){
  var itemObj = this;
  var audio = new Audio();
  itemobj.media = audio;
  rsobj.rs[itemobj.key] = audio;

  var filePath = itemobj.src;
  var folderPath = filePath.substr(0, filePath.lastIndexOf('.'));

  var source = document.createElement('source');
  if(audio.canPlayType('audio/mpeg')){
    source.type = 'audio/mpeg';
    source.src = folderPath + '.mp3';
  }else if(audio.canPlayType('audio/ogg')){
    source.type = 'audio/ogg';
    source.src = folderPath + '.ogg';
  }else if((audio.canPlayType('audio/wav'))){
    source.type = 'audio/wav';
    source.src = folderPath + '.wav';
  }
  audio.appendChild(source);

  ResourceLoader.mediaCheck(rsobj, itemobj, callback);
}

JavaScript 排序

comb sort

分个组分别冒泡

Array.prototype.combSort = function () {
  var factor = 0.8
  var gap = this.length
  var swapped = true
  var i
  var temp
  while (gap > 1 || swapped) {
    if (gap > 1) {
      gap = Math.floor(gap * factor)
    }
    swapped = false
    for (i = 0; gap + i < this.length; i++) {
      if (this[i] > this[i + gap]) {
        temp = this[i]
        this[i] = this[i + gap]
        this[i + gap] = temp;
        swapped = true
      }
    }
  }
  return this
}

mac 安装redis

http://yijiebuyi.com/blog/d8ab4b444c16f42cefe30df738a42518.html

(1)下载 redis http://redis.googlecode.com/files/redis-2.8.7.tar.gz 解压到当前目录.
or

curl -O http://redis.googlecode.com/files/redis-2.8.7.tar.gz
sudo tar -zxf redis-2.8.7.tar.gz

(2)

mv redis-2.8.7 redis
cd redis/
sudo make
sudo make test
sudo make isntall

(4)你会在redis 目录里找到一个 redis.conf 的配置文件,打开编辑此配置文件,找到 dir . 这一行配置.

此配置是将内存中的数据写入一个文件,这个数据库文件要保存到什么地方 就是这个配置项起到的作用.

我在mac根目录下创建了 opt 的文件夹(注意此文件夹必须有可读写权限)

所以这一行的配置是 dir /opt/redis/

修改后保存配置文件,同时将配置文件移动到 /etc 目录下.

sudo mv redis.conf /etc

(5) 上面第三步 make install 成功后,你就应该在这个目录下看到redis

/usr/local/bin/redis-server

(6) 尝试启动一下 redis

/usr/local/bin/redis-server /etc/redis.conf

如果运行成功,你会看到下面的redis启动服务画面.

(7) 连接redis

$ /usr/local/bin/redis-cli

JQ实现视差效果

这次的主角是jQuery-Parallax

实现原理就是在window的resize和scroll事件触发时调整当前所在viewport中的元素的背景图片定位,很简单。

本来想加点东西进去,比如让背景横向和斜向移动,产生的一个问题是,背景水平定位一般都是用百分比,就是需要每次调用去修改其x定位, 修改不是问题,问题是如何和y的数值还有croll的值进行一个比较合理的配合。这样写来都要重写了,尝试了一下午,失败告终。

还有个问题是必须预加载图片,才能显示,不然实在难看。

demo

AngularJs初体验

AngularJs官网

首先是hello例子

最重要的开头的

<html ng-app>

这个ng-app主要是让angular激活当前页面,

然后是

<input type="text" ng-model="yourName" placeholder="Enter a name here">
<hr>
<h1>Hello {{yourName}}!</h1>

这个ng-model就是定义一个model,能够让{{yourName}}这个模型的值实时变化。

卧槽,好爽的感觉!


然后就是一个todo list的例子

这里主要加入了一个控制器TodoCtrl,更重要的是这个$scope的参数,官方说是存入了模型的数据,是控制器和视图之间的胶水,其他不难理解,主要都是视图与控制器之间的缠绵。

写完这个,感觉在angular这个媒婆的帮助下,原本各顾各的js和html能很好相处起来,整个氛围没有原生或jq那样的生硬。


接下来要进入和后端的情感纠纷环节了。要断网了,明日继续。

【译】html5游戏入门

【译】html5游戏入门

原文链接

简介

如果你想用canvas做个游戏,那么来对地方了。

但是但是你至少知道javascript怎么拼写(╯‵□′)╯︵┻━┻

既然没问题,那先来一下或者下载

创建canvas标签

废话不多说,我们必须创建一个canvas标签,简单起见,用一下不喜欢的jQuery

var CANVAS_WIDTH = 480;
var CANVAS_HEIGHT = 320;

var canvasElement = $("<canvas width='" + CANVAS_WIDTH + 
                      "' height='" + CANVAS_HEIGHT + "'></canvas>");
var canvas = canvasElement.get(0).getContext("2d");
canvasElement.appendTo('body');

游戏循环

为了能够让游戏平滑动画,我们用30帧的频率。

var FPS = 30;
setInterval(function() {
  update();
  draw();
}, 1000/FPS);

现在我们可以先给这两个函数放置play,重要的是setInterval函数会定期照顾他们的。

hello world

现在我们有了这个循环,让我们开始画东西吧~

function draw() {
  canvas.fillStyle = "#000"; // Set color to black
  canvas.fillText("Sup Bro!", 50, 50);
}

注意:确认修改之后刷新一下,万一哪里不对,代码变的少还能看出哪里不对。

如果没错,那么显示的是静止的字母,虽然好看,但我们已经有了动画循环,所以我们应该很容易让他动起来。

var textX = 50;
var textY = 50;

function update() {
  textX += 1;
  textY += 1;
}

function draw() {
  canvas.fillStyle = "#000";
  canvas.fillText("Sup Bro!", textX, textY);
}

现在如果没出错,那么字母应该在移动,但是有残影出现。想想为什么会这样,因为我们没有清除之前的画面呢,so 我们加点清除画布的代码。

function draw() {
  canvas.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
  canvas.fillStyle = "#000";
  canvas.fillText("Sup Bro!", textX, textY);
}

现在可以看到字母在屏幕上移动了,恭喜你,你已经快入门了。让我们继续。

创建玩家

接下来创建一个物体用来给玩家控制,我们创建了一个简单的object:

var player = {
  color: "#00A",
  x: 220,
  y: 270,
  width: 32,
  height: 32,
  draw: function() {
    canvas.fillStyle = this.color;
    canvas.fillRect(this.x, this.y, this.width, this.height);
  }
};

我们简单地着色了这个物体,当我们清除画布的时候,画上这个物体。

function draw() {
  canvas.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
  player.draw();
}

键盘控制

使用jQuery HotKeys

使用jQuery HotKeys,这个插件提供了简单的键盘输入检测
我们可以这么绑定事件

$(document).bind("keydown", "left", function() { ... });

不用想哪个按键是哪个号码真舒服,我们刚才实现了“当玩家按上的时候,做一些事情”,碉堡的插件!

玩家的移动

键盘输入检测已经完成了,但我们还要处理键盘输入之后要做什么。
你可能会想使用事件驱动的方式去处理键盘输入,但是这样做系统不一,按键效果不一样,而且脱离了动画循环呢,这样做就可以跨系统了,保证了一致性,也让游戏更平滑了。

有一个好消息,我们有一个key_status.js的文件,提供了类似keydown.left等等。去下载的文件里找

现在我们可以去查询是否有按键了,然后我们就这么写:

function update() {
  if (keydown.left) {
    player.x -= 2;
  }

  if (keydown.right) {
    player.x += 2;
  }
}

这样玩家可以控制了。

你可能注意到玩家可以跑出屏幕,让我们限制一下玩家的位置,而且似乎控制速度有点慢,我们顺便加加速。

function update() {
  if (keydown.left) {
    player.x -= 5;
  }

  if (keydown.right) {
    player.x += 5;
  }

  player.x = player.x.clamp(0, CANVAS_WIDTH - player.width);
}

clamp这个函数可以在下载的util.js里看到

然后我们加点炮弹进去。

function update() {
  if (keydown.space) {
    player.shoot();
  }

  if (keydown.left) {
    player.x -= 5;
  }

  if (keydown.right) {
    player.x += 5;
  }

  player.x = player.x.clamp(0, CANVAS_WIDTH - player.width);
}

player.shoot = function() {
  console.log("Pew pew");
  // :) Well at least adding the key binding was easy...
};

添加更多物体

子弹
我们需要一个数组放子弹

var playerBullets = [];

接下来我们创建一个子弹原型

function Bullet(I) {
  I.active = true;

  I.xVelocity = 0;
  I.yVelocity = -I.speed;
  I.width = 3;
  I.height = 3;
  I.color = "#000";

  I.inBounds = function() {
    return I.x >= 0 && I.x <= CANVAS_WIDTH &&
      I.y >= 0 && I.y <= CANVAS_HEIGHT;
  };

  I.draw = function() {
    canvas.fillStyle = this.color;
    canvas.fillRect(this.x, this.y, this.width, this.height);
  };

  I.update = function() {
    I.x += I.xVelocity;
    I.y += I.yVelocity;

    I.active = I.active && I.inBounds();
  };

  return I;
}

但玩家射击时,我们应该实例子弹,然后添加到子弹数组中.

player.shoot = function() {
  var bulletPosition = this.midpoint();

  playerBullets.push(Bullet({
    speed: 5,
    x: bulletPosition.x,
    y: bulletPosition.y
  }));
};

player.midpoint = function() {
  return {
    x: this.x + this.width/2,
    y: this.y + this.height/2
  };
};

我们需要把子弹的动画添加到没帧的动画里,为了能让子弹变成无限的效果,我们过滤了子弹数组,只保留了激活的子弹.同时删除了已经撞到敌人的子弹.

function update() {
  ...
  playerBullets.forEach(function(bullet) {
    bullet.update();
  });

  playerBullets = playerBullets.filter(function(bullet) {
    return bullet.active;
  });
}

最后一步就是画子弹了.

function draw() {
  ...
  playerBullets.forEach(function(bullet) {
    bullet.draw();
  });
}

敌人
现在我们要像添加子弹一样添加敌人.

 enemies = [];

function Enemy(I) {
  I = I || {};

  I.active = true;
  I.age = Math.floor(Math.random() * 128);

  I.color = "#A2B";

  I.x = CANVAS_WIDTH / 4 + Math.random() * CANVAS_WIDTH / 2;
  I.y = 0;
  I.xVelocity = 0
  I.yVelocity = 2;

  I.width = 32;
  I.height = 32;

  I.inBounds = function() {
    return I.x >= 0 && I.x <= CANVAS_WIDTH &&
      I.y >= 0 && I.y <= CANVAS_HEIGHT;
  };

  I.draw = function() {
    canvas.fillStyle = this.color;
    canvas.fillRect(this.x, this.y, this.width, this.height);
  };

  I.update = function() {
    I.x += I.xVelocity;
    I.y += I.yVelocity;

    I.xVelocity = 3 * Math.sin(I.age * Math.PI / 64);

    I.age++;

    I.active = I.active && I.inBounds();
  };

  return I;
};

function update() {
  ...

  enemies.forEach(function(enemy) {
    enemy.update();
  });

  enemies = enemies.filter(function(enemy) {
    return enemy.active;
  });

  if(Math.random() < 0.1) {
    enemies.push(Enemy());
  }
};

function draw() {
  ...

  enemies.forEach(function(enemy) {
    enemy.draw();
  });
}

加载和添加图片

虽然目前这些方块飞来飞去看起来很酷,但有图片就更酷了。我们使用了一个叫sprite.js的文件,可以从下载的文件里看到。

player.sprite = Sprite("player");

player.draw = function() {
  this.sprite.draw(canvas, this.x, this.y);
};

function Enemy(I) {
  ...

  I.sprite = Sprite("enemy");

  I.draw = function() {
    this.sprite.draw(canvas, this.x, this.y);
  };

  ...
}

碰撞检测

我们已经有了很多敌人飞来飞去了,但他们没有交互呢mb打不到他们,我们是时候加点碰撞检测了.
让我们使用一个简单的方法检测:

function collides(a, b) {
  return a.x < b.x + b.width &&
         a.x + a.width > b.x &&
         a.y < b.y + b.height &&
         a.y + a.height > b.y;
}

我们需要检测如下两种碰撞:

  1. 玩家子弹和敌方飞船
  2. 玩家和敌方飞船

让我们给update加入处理碰撞之后的处理

function handleCollisions() {
  playerBullets.forEach(function(bullet) {
    enemies.forEach(function(enemy) {
      if (collides(bullet, enemy)) {
        enemy.explode();
        bullet.active = false;
      }
    });
  });

  enemies.forEach(function(enemy) {
    if (collides(enemy, player)) {
      enemy.explode();
      player.explode();
    }
  });
}

function update() {
  ...
  handleCollisions();
}

现在我们需要给敌方飞船和玩家添加爆炸效果,爆炸的同时会移除

function Enemy(I) {
  ...

  I.explode = function() {
    this.active = false;
    // Extra Credit: Add an explosion graphic
  };

  return I;
};

player.explode = function() {
  this.active = false;
  // Extra Credit: Add an explosion graphic and then end the game
};

声音

为了可玩性,我们将要添加声音效果进去,我们用到sound.js这个文件,让事情变得非常简单。

player.shoot = function() {
  Sound.play("shoot");
  ...
}

function Enemy(I) {
  ...

  I.explode = function() {
    Sound.play("explode");
    ...
  }
}

使用这些API就能很快地完成一个简单的游戏.

告别

再说一下游戏地址,也可以下载

well,我希望你开始喜欢用js和html5写简单的游戏,随着学习的深入,将来会有更多地挑战呢.

参考文献

HTML5 Canvas Cheat Sheet
HTML5 Game Engines

译后感

第一次完整的翻译一篇文章,真蛋疼有些句子感觉不好翻,就随便糊弄一下,BTW,我也按这个教程写了例子,好像写完还有很多问题呢(逃

perfectly make element to be dragable

demo

<style type="text/css">
html,body{overflow:hidden;}
body,div,h2,p{margin:0;padding:0;}
body{color:#fff;}
p{padding:0 10px;margin-top:10px;}
span{color:#ff0;padding-left:5px;}
#box{position:absolute;width:300px;height:150px;background:#333;border:2px solid #ccc;top:50%;left:50%;}
#box h2{height:25px;cursor:move;background:#222;border-bottom:2px solid #ccc;text-align:right;padding:0 10px;}
#box h2 a{color:#fff;font:12px/25px Arial;text-decoration:none;outline:none;}
</style>
<div id="box">
    <h2><a href="javascript:;">点击回放拖动轨迹</a></h2>
    <p><strong>Drag:</strong><span></span></p>
    <p><strong>offsetTop:</strong><span></span></p>
    <p><strong>offsetLeft:</strong><span></span></p>
</div>
<script>
    var oBox=document.getElementById('box');
    var title=box.getElementsByTagName('h2')[0];
    var dragText=box.getElementsByTagName('span')[0];
    var topText=box.getElementsByTagName('span')[1];
    var leftText=box.getElementsByTagName('span')[2];
    var bDragable=false;
    var disX=0;
    var disY=0;
    // 记录轨迹
    var pos=[{x:oBox.offsetLeft,y:oBox.offsetTop}];
    var oA=box.getElementsByTagName('a')[0];
    // 开启拖拽
    title.onmousedown=function(){
        var event=event||window.event;
        bDragable=true;
        // 扣除鼠标离边缘的位置距离
        disX=event.clientX-oBox.offsetLeft;
        disY=event.clientY-oBox.offsetTop;
        // 设置鼠标捕获范围
        this.setCapture&&this.setCapture();
        return false;
    }
    // 开始拖拽
    document.onmousemove=function(){
        if(!bDragable)
            return;
        var event=event||window.event;
        var left=event.clientX-disX;
        var top=event.clientY-disY;
        var maxLeft=document.documentElement.clientWidth-oBox.offsetWidth;
        var maxTop=document.documentElement.clientHeight-oBox.offsetHeight;

        left=left<0?0:left;
        left=left>maxLeft?maxLeft:left;
        top=top<0?0:top;
        top=top>maxTop?maxTop:top;
        // console.log(left+" "+top);
        oBox.style.left=left+"px";
        oBox.style.top=top+"px";

        pos.push({x:left,y:top});
        status();
        return false;
    }
    // 关于这个window.blur和onloasecapture不太清楚
    document.onmouseup=window.blur=title.onlosecapture=function(){
        bDragable=false;
        title.releaseCapture&&title.releaseCapture();
        status();
    }
    oA.onclick=function(){
        if(pos.length==1)return;
        var timer=setInterval(function(){
            var pop=pos.pop();
            if(pop){
                oBox.style.left=pop.x+"px";
                oBox.style.top=pop.y+"px";
                status();
            }else{
                clearInterval(timer);
            }
        },30);
    }
    oA.onmousedown=function(event){
        var event=event||window.event;
        event.cancelBubble=true;
    }
    status();
    function status(){
        dragText.innerHTML=bDragable;
        topText.innerHTML=oBox.offsetTop;
        leftText.innerHTML=oBox.offsetLeft;
    }
</script>

compass sprite

例子为@import "icon/*.png";,下面的就是文件夹名称,例子为icon

所有icon必须是非交错的png,否则会报没有unpack属性的错误,非交错就是用ps保存png的时候,会有
image
的选项

基本设置
比如目前my-icons有4张图片
images/my-icons/new.png
images/my-icons/edit.png
images/my-icons/save.png
images/my-icons/delete.png
然后在scss文件中

@import "compass/utilities/sprites";
@import "my-icons/*.png";
@include all-my-icons-sprites;

就可以用.my-icons-delete使用delete的背景图片

或者 可以用这种

@import "my-icons/*.png";

.actions {
  .new    { @include my-icons-sprite(new);    }
  .edit   { @include my-icons-sprite(edit);   }
  .save   { @include my-icons-sprite(save);   }
  .delete { @include my-icons-sprite(delete); }
}

这样看起来更舒服点

选项

  • $<map>-spacing合成图片之间的margin e.g $icon-spacing: 20px
  • $<map>-repeat背景图片的重复like $icon-repeat: repeat-x
  • $<map>-position背景定位,比如100%,就是把图片都往右边靠,宽度为最大的那张
  • $<map>-clean-up是否在每次创建新的图片时,删去旧的图片
  • $<map>-sprite-dimensions
    $<map>-sprite-base-class
    $<map>-<sprite>-spacing
    $<map>-<sprite>-repeat
    $<map>-<sprite>-position
    没明白什么用

有组成方式的选项
选项必须放在该import前面
$[map]-layout属性有Vertical(default,竖着放),Horizontal(横着放),Diagonal(从右上到左下),Smart(紧凑)
e.g $[map]-layout:smart;会把图片都紧凑的压在一起,测试该选项会导致$<map>-spacing失效

比如要给一个a加入4种状态时候的图片,e.g
icons:
my-buttons/glossy.png
my-buttons/glossy_hover.png
my-buttons/glossy_active.png
my-buttons/glossy_target.png

@import "my-buttons/*.png";

a {
  @include my-buttons-sprite(glossy)
}

a标签就自动获得4个状态的样式
要关闭这个功能在include前面加$disable-magic-sprite-selectors:true;

其实很烦写标题

今天把node web这边书的第四章看玩了,虽然有些问题,程序不能运行,不过,基本功能还是有的。

微软学院的h5和c3的教程第4章看完,然后8道题全部答对了。

本来是想把fakefish.me这个域名直接连到fakefish.github.com上,不过好像出了点问题,今天不太想弄这个了,周六考6级,这个过去了再来整这个问题吧。

对,差点忘记了,今天看上面这个视频的时候看到了array的map方法和forEach方法,想区分一下,在mdn上看到了一个用es5的object的一些新方法用来复制的一个例子,已经收录在clone.js里了。

不过我发现每天这样写写其实挺好的,有助于学习,不过担心的是要是哪天玩了一天的游戏或者其他什么的,没学习技术,就不知道写什么了。

svn tips

svn copy http://example.com/repos/myproject/trunk http://example.com/repos/myproject/branches/releaseForAug -m 'create branch for release on August'
svn merge http://example.com/repos/myproject/branches/releaseForAug
svn merge  http://example.com/repos/myproject/branches/releaseForAug -r150:HEAD

玩了几天

今天圣诞。
昨天几个人去吃烧烤了。
前天去杭州考微软的css3和html5的测试。
大前天六级。

今天撸了几句node,突然commit不了了,莫名其妙。

start shell and mongoDB

心血来潮,早上看了点mongoDB,晚上看了点shell

比如> >> <
比如 tput stty
比如alias declare exec date

其实刚才打这些指令的时候好像有些忘记了是干嘛用的

借了本mongoDB和HeadFirstAjax

看了下现在手头上的书
1.js权威指南第六版 看到第六章
2.深入浅出cs 看到第二章,其实去过官网做过点练习
3.linux shell脚本攻略 第一章=。=
4.mongoDB权威指南 第二章
5.HeadFirst Ajax 第二章
6.node web开发 5.2节
7.html5游戏 已经不想看了,对canvas没什么好感
寒假就计划下都看完,都看完会不会太不可能
不管怎么样,基本薄的应该能看完
对了,差点忘记了那本操作系统,之前写了8天,寒假把书拿回来,把剩下的23天的代码抄完

接下来要复习java c# 网络原理 操作系统 应用文

最讨厌期末考试了

突然想起来,觉得如果每周写一篇纯英语的日记或者周记,有助于提升英语文字表达能力吧,那就每周日吧。

简单的requestAnimationFrame方法

(function(){
  var lastTime = 0;
  var vendors = ['ms', 'moz', 'webkit', 'o'];
  for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x){
    window.requestAnimation = window[vendors[x] + 'RequestAnimationFrame'];
    window.cancelAnimtionFrame = 
      window[vendors[x] + 'CancelAnimationFrame'] || 
      window[vendors[x] + 'CancelRequestAnimtionFrame'];
  }

  if(!window.requestAnimationFrame)
    window.requestAnimationFrame = function(callback, element){
      var currTime = new Date().getTime();
      var timeToCall = Math.max(0, 16 - (currTime - lastTime));
      var id = window.setTimeout(function(){ callback(currTime + timeToCall) ;},timeToCall);
      lastTime = currTime + timeToCall;
      return id;
    };
  if(!window.cancelAnimationFrame)
    window.cancelAnimationFrame = function(id){
      clearTimeout(id);
    }
})();

垂直居中的解决方案

在alice中,用了display:table来让目标显示成表格的样子,比如demo1

但这个方法就是感觉太麻烦了,然后找到一个神奇的方法demo2,感觉似乎是hack级别的方法呢。

ajax utils.js

function createRequest() {
  try {
    request = new XMLHttpRequest();
  } catch (tryMS) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (otherMS) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        request = null;
      }
    }
  } 
  return request;
}

其实很烦写标题

今天把node web这边书的第四章看玩了,虽然有些问题,程序不能运行,不过,基本功能还是有的。

微软学院的h5和c3的教程第4章看完,然后8道题全部答对了。

本来是想把fakefish.me这个域名直接连到fakefish.github.com上,不过好像出了点问题,今天不太想弄这个了,周六考6级,这个过去了再来整这个问题吧。

对,差点忘记了,今天看上面这个视频的时候看到了array的map方法和forEach方法,想区分一下,在mdn上看到了一个用es5的object的一些新方法用来复制的一个例子,已经收录在clone.js里了。

不过我发现每天这样写写其实挺好的,有助于学习,不过担心的是要是哪天玩了一天的游戏或者其他什么的,没学习技术,就不知道写什么了。

刚才**了,提交没选标签,然后就找不到了。。然后又提交了一次,之后发现前面一篇了。。关掉那篇=。=

Preview an image before it is uploaded

link

Please take a look at the sample JS code below:

function readURL(input) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#imgInp").change(function(){
    readURL(this);
});

and the associated HTML:

<form id="form1" runat="server">
    <input type='file' id="imgInp" />
    <img id="blah" src="#" alt="your image" />
</form>
Also, you can try this sample here.

match some parameters in domain

var reg=/uid=([^&]*)(&|$)/; 
// such like http://127.0.0.1/fcms/v0.1/uc.php?uid=1021
// i want to get the parameters of uid 
var uid=url.match(reg)[1];
// return uid=1021,1021
// so i need the second one

get activated object and addEventHandler

function getActivatedObject(e) {
  var obj;
  if (!e) {
    // early version of IE
    obj = window.event.srcElement;
  } else if (e.srcElement) {
    // IE 7 or later
    obj = e.srcElement;
  } else {
    // DOM Level 2 browser
    obj = e.target;
  }
  return obj;
}
function addEventHandler(obj, eventName, handler) {
  if (document.attachEvent) {
    obj.attachEvent("on" + eventName, handler);
  } else if (document.addEventListener) {
    obj.addEventListener(eventName, handler, false);
  }
}

functional javascript

function pipeline(seed/*, args */) {
  return _.reduce(_.rest(arguments),
    function(l, r) { return r(l); },
    seed);
}

计算任何一日属一星期中哪一日

jsbin
用的主要是叫 蔡勒公式

var zeller = function (year,month,day){
  var c = parseInt(year/100,10);
  var y = parseInt(year%100,10);
  var m;
  if(month<3){
    y=y-1;
    month = month + 12;
  }
  m = parseInt(month,10);
  var d = parseInt(day,10);
  var w=y+Math.floor(y/4)+Math.floor(c/4)-2*c+Math.floor(26*(m+1)/10)+d-1;
  w = w % 7;
  if(w<0){
    w = w+7;
  }

  return w;
};

关于react-native的认知

什么是react-native

不再阐述 http://facebook.github.io/react-native/

目前主流的移动端开发模式

做手机端目前主流是 native 和 hybrid 两种方案,前者优点是性能好,能做的事情多,缺点是需要做各平台定制代码,升级频率的问题,后者优点是能直接升级,能灰度能 ab,缺点是性能差,能做的事情少。
rn 其实和 react 没啥太大的关系,只是用了 react 的语法,所以语法这一层可以换成vue(weex)或者ng(http://angular.github.io/react-native-renderer/) ,甚至是 Nova.js。

大致的结构、原理及特性

最底层是系统,然后是 Objective-C,OC 通过 JSBridge 把接口给最上层的 JS。这里面还有 JS 把注册完的内容通过 JSCore 引擎解析还给 OC 。注意,这里用了一个词叫注册,之所以性能和 Native 相差无几是因为 JS 是跑在一个专门给 JS 开的线程里,所以一个 RN 应用在运行时一般是开着两个线程,偶尔有个网络请求会再开一个网络的线程,由于移动端所有的代码都是异步的,等待系统调用,事件发生了才会去 JS 线程里看看有没有对应处理的东西,因此 JS 的代码更加是异步的异步。所以这种情况下,有些事情会变得很奇怪,比如我在一个 ScrollView 里监听滚动事件做一个动画啥的,会发生页面滚动了但动画延迟了,不是因为 RN 性能不行,而是这种机制下,滚动是系统的,动画是 JS 的,里面差了至少两个线程,要解决这个问题,就是滚动也是 JS 去做,干脆一起延迟。还有个经典的问题,iOS 里有 TableView,各种自动优化,但 RN 里的 ListView 没有用 TableView 的优化,也是因为这个,这种机制算起来是一把双刃剑。

为什么要使用 rn

开发效率

先举个例子,在 RN 中发个网络请求我们直接用 fetch api,而在 OC 中,我们需要新建一个线程去跑任务,然后再切回主线程

[self.spinner startAnimating];

NSURLRequest *request = [NSURLRequest requestWithURL:self.imageURL];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSURLSessionDownloadTask *task =
[session downloadTaskWithRequest:request
               completionHandler:^(NSURL *localfile, NSURLResponse *response, NSError *error) {
                   if (!error) {

                       // In the case of URL was changed to download smth different.
                       if ([request.URL isEqual:self.imageURL]) {

                           // Create image based on local file path.
                           UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:localfile]];

                           // Set image to be displayed in the main queue.
                           dispatch_async(dispatch_get_main_queue(), ^{

                               self.image = image;
                           });

                           // Alternative way to do it in the main queue.
                           /*
                           [self performSelectorOnMainThread:@selector(setImage:)
                                                  withObject:image
                                               waitUntilDone:NO];
                            */
                       }
                   }
               }];
[task resume];

上面的代码是显示加载动画,然后下载一个远程的图片,开个线程跑,跑完取回图片,再同步主线程。

节约多少代码量。

还有最重要是跨平台性,安卓和 iOS 上的业务代码基本是一样的,这些细微的差异可以通过架构去做掉,所以以前可能每个平台各需要2个工程师,外加一个前端,现在一个平台一个,前端一个就可以搞定而且开发效率有极大的提升,业务的迭代一般也只要改前端的代码。

性能

rn 的性能比 Native 略微差一点,可以忽略不计,相比 hybrid 方案好很多。暂没有数据可以提供。

热更新

虽然 rn 的性能比 hybrid 好很多,但是 hrbrid 有 web 方式的优点,就是可以直接热更新,或者 AB 测试,而 Native 不能直接热更新,还需要有个周期去等,虽然 iOS 上的更新速度还挺快,安卓端肯定没有这么好。

由于前面讲的 rn 的机制,js 不是跑在主线程,因此也无法在后台跑检查更新然后直接更新,虽然有code-push 但它的检查是在启动的时候做的,有更新就直接下载了,或者弹个提示更新,确定之后直接下载,不能做一些更佳细致的处理,不过如果有移动端架构的支持,可以后台跑个监控网络情况再更新。

这种机制下,可以做全量、灰度或者 AB 都可以。

文件大小

具体没有做过调查,由于代码量的大量下降,理论上会比同功能的 Native 小一点,而且可以做增量更新,虽然安卓端有插件机制,在这方面优势不大。听新美大的朋友说之前的 app 是 100+m,部分转 rn 之后是 90+m。

学习成本

去哪儿在这方面的成本是,十几个人花了三个多月才完成平台代码的改造。

官方代码的局限

作为社区开源框架,在功能方面需要有所考量,但是具体应用到业务上需要做定制化,需要移动端同学的努力。

移动端

需要学习一点 react 的知识,不过庆幸的是 react 有 jsx 的语法,对安卓的同学来讲,只不过是另一种 xml 的写法。

站在前端的角度来看,这个方面的学习成本不高。对移动端同学来讲,最大的成本在于需要了解 rn 的机制,以及一些相关的源码,需要对框架进行改造。

前端

对前端来讲,react 本身学习成本不高,而且 react 生态圈大部分是基于 web,对生态圈不需要太多的额外的学习,可能唯一要学透的是 redux。其他,需要对 rn 的机制需要有所了解,其他可以不用完全掌握。

高校土特产项目的采访

ccttc
这是一个由一位高校学生做的校园电商项目,成立至今已过去一年多的时间.销量不高,但是运营的不错.
笔者有幸能够采访到这个网站的创始人,以下是采访内容:
(fakefish:笔者,early he:绍兴土特产网站创始人)

fakefish 14:07:27
我可以采访你了么
early he 14:15:43
可以
fakefish 14:16:31
最开始是什么时候开始这个项目?
一开始做土特产的这个网站起因还记得么?

early he 14:17:10
最早应该是12年1月份的时候
fakefish 14:17:41
起因呢?
early he 14:17:49
那时候做特产刚好人手不足就我一个人 然后每天电话接到爆
随身都要带着纸和笔
early he 14:18:51
就想通过做个网站分流下订单
fakefish 14:18:55
那之前是几个人在做这个事?
early he 14:19:14
最早是3个人后来他们大四都走了 就我一个
而且那时候刚好准备做开去 光靠传统的发传单宣传太累了
fakefish 14:19:42
那去年的营销额怎么样
early he 14:19:52
而且很多人想看看照片
最近一次?
fakefish 14:20:34
年销售额 或者周月销量
或者最高日销量
early he 14:21:12
最近一次 总的也就做了不到一周
8000不到点
客单在90
fakefish 14:22:17
这个网站在创立之后 总共带来8k的营销额?
每位顾客平均消费90?
early he 14:22:55
不是 所有的 加上电话订单的 因为现在统计也都放在网站上了
都是电子出单了

fakefish 14:23:26
网站的销量在总销量中比例如何?
early he 14:23:48
40%
fakefish 14:24:10
营销方式有哪些呢?
early he 14:24:29
人传人...
人人网 传单 然后各个校区都会有代理
fakefish 14:25:26
物流是如何安排的呢?
early he 14:25:53
每天送一次 下午5点
fakefish 14:26:06
由厂家直送么?
early he 14:26:16
送到校区的代理那边 然后由代理送
**我们先去拿货 **
fakefish 14:26:53
那现在算上代理有多少人在做这方面的工作?
early he 14:27:52
4个人
因为有些人会负责多个校区
他们下面可能有些帮忙的
因为这个是季节性的 所以在人方面不会很多
fakefish 14:30:12
能不能分享点这方面有关的喜怒哀乐?
early he 14:30:39
之前一个人做的时候 每天要拿很多货 然后下雨天...
fakefish 14:30:56
很苦逼啊
early he 14:31:00
然后骑车 货用下巴盯着
淋雨回来
fakefish 14:31:58
那有什么很高兴的事?
early he 14:32:32
有次有个湖州的电话打来 说看到我们网站
然后买了一大堆~ 有很多玻璃的 然后我从来没寄过这么多
然后就怕碎掉
fakefish 14:34:44
走的淘宝付款么
early he 14:37:14

fakefish 14:38:43
现在你在杭州实习,那这个项目是否已经转给他人运营了?
early he 14:40:05
恩 给下面的人了
fakefish 14:40:29
对这个网站的发展有什么展望么?
early he 14:41:21
那个网站的初衷就是实用 现在已经基本达到期望了 之后应该不会有太大的改动
fakefish 14:41:25
谢谢,我的采访结束了.

PS:受嘉宾委托,不留联系方式和网站地址了.

foreach函数的实现

// http://www.cnblogs.com/rubylouvre/archive/2009/11/10/1599978.html
// object: 要处理的对象,数组,字符串
// block: 处理的函数
// context: 上下文,函数的参数
// fn: 恒为Function

function forEach(object, block, context, fn) {
  if (object == null) return;
  if (!fn) {
    if (typeof object == "function" && object.call) {
      //遍历普通对象
      fn = Function;
    } else if (typeof object.forEach == "function" && object.forEach != arguments.callee) {
      //如果目标已经实现了forEach方法,则使用它自己的forEach方法(如标准游览器的Array对象)
      object.forEach(block, context);
      return;
    } else if (typeof object.length == "number") {
      // 如果是类数组对象或IE的数组对象
      _Array_forEach(object, block, context);
      return;
    }
  }
  _Function_forEach(fn || Object, object, block, context);
};

function _Array_forEach(array, block, context) {
  if (array == null) return;
  var i = 0,length = array.length;
  if (typeof array == "string") {
    for (; i < length; i++) {
      block.call(context, array.charAt(i), i, array);
    }
  }else{
    for (;i < length; i++) {
      block.call(context, array[i], i, array);
    }
  }
};


function _Function_forEach(fn, object, block, context) {
  // 这里的fn恒为Function
  for (var key in object) {
     //只遍历本地属性
     if (object.hasOwnProperty(key)) {
      //相当于  block(object[key], key)
      block.call(context, object[key], key, object);
    }
  }
};

function print(el,index){
  alert(index+"  :  "+el)
}
forEach ([1, 2, 3], print);
forEach ({a: "aa", b: "bb",c: "cc"}, print);
forEach ("fakefish", print);
forEach(document.styleSheets,function(el){
  if(el.href) alert(el.href)
});

判断数组

Object.prototype.isArray=function(){
  if (typeof this == 'object') {
    var result = this.constructor.toString().match(/array/i);
    return (result != null);
  }
  return false;
}
[].isArray(); // true
{}.isArray(); // error ?

ajax in Prototype framework

// in Prototype
function checkUsername() {
  var usernameObject = $("username");
  usernameObj.className = "thinking";

  var username = escape(usernameObj.value);
  new Ajax.Request("checkName.php", {
    method: "get",
    parameters: "username=" + username,

    onSuccess: function(transport) {
    // transport is request object in Prototype
      if (transport.responseText == "okey") {
        $("username").className = "approved",
        $("register").disabled = false;
      } else {
        var usernamenameObject = $("username");
        usernameObject.className = "denied";
        usernameObject.focus();
        usernameObject.select();
        $("register").disabled = true;
      }
    },
    onFailure: function() { alert("Error in validation."); }
  });
}

简单的图片加载器

var imageLoader = {
  loaded : true,
  loadedImage : 0,
  totalImages : 0,
  load : function(url){
    this.totalImages++;
    this.loaded = new Image();
    var image = new Image();
    image.src = url;
    image.onload = function(){
      imageLoader.loadedImage++;
      if(imageLoader.loadedImages === imageLoader.totalImages(){
        imageLoader.loaded = true;
      }
    }
    return image;  
  }
}

css3画安卓机器人和放大镜的实现

css3画安卓机器人
放大镜的实现

下面是安卓的实现

<div class="android">
    <div class="head">
        <div class="l_ant"></div>
        <div class="r_ant"></div>
        <div class="l_eye"></div>
        <div class="r_eye"></div>
    </div>
    <div class="body">
        <div class="l_arm"></div>
        <div class="r_arm"></div>
        <div class="l_leg"></div>
        <div class="r_leg"></div>
    </div>
  </div>
div{
  margin: 0;
  padding: 0;
}
div div{
  background:#a4ca39;
  position: relative;
}

.android{
  height: 404px;
  width: 334px;
  margin: 0 auto;
}
.head{
  width: 220px;
  height: 100px;
  top: 32px;

  border-radius:110px 110px 0 0 ;

  -webkit-transition: all 0.1s ease-in;
}
.l_eye,.r_eye{
  background:#fff;
  width: 20px;
  height: 20px;
  position: absolute;
  top: 42px;

  border-radius:10px;
}
.l_eye{
  left: 50px;
}
.r_eye{
  right: 50px;
}

.l_ant,.r_ant{
  width: 6px;
  height: 50px;
  position: absolute;
  top: -34px;

  border-radius:3px;
}
.l_ant{
  left: 50px;
  -webkit-transform:rotate(-30deg);
}
.r_ant{
  right: 50px;
  -webkit-transform:rotate(30deg);
}

.body{
  width: 220px;
  height: 184px;
  top: 40px;

  border-radius:0 0 25px 25px;
}

.l_arm,.r_arm,.l_leg,.r_leg{
  width: 50px;
  position: absolute;
  -webkit-transition:all 0.1s ease-in;
}
.l_arm,.r_arm{
  height: 150px;
  border-radius:25px;
}
.l_leg,.r_leg{
  height: 80px;
  top: 182px;
  border-radius:0 0 25px 25px;
}
.l_arm{
  left: -58px;
}
.r_arm{
  right: -58px;
}
.l_leg{
  left: 45px;
}
.r_leg{
  right: 45px;
}

.head:hover{
  -webkit-transform:rotate(-5deg) translate(-4px, -8px);
}
.l_arm:hover{
  -webkit-transform:rotate(15deg) translate(-14px, 0);
}
.r_arm:hover{
  -webkit-transform:rotate(-15deg) translate(14px, 0);
}

test

| Year || Temperature (low) || Temperature (high) ||
|| 1900 || -10 || 25 ||
|| 1910 || -15 || 30 ||
|| 1920 || -10 || 32 ||

About Me

产品说明书

中文名:王佳裕

英文名:fakefish

简介:此人个人不高,却有半颗企图改变世界的心。略懂JS。

在校无知大学生一枚,2010年入学,无耻地以处男身份呆在某大学中。

爱好UE、喜欢做PM、懂点css、在学js,曾被IE6玩死。

无耻的loli控。

爱好动漫,喜欢画画,可惜画的不好,缺少艺术创造细胞,会欣赏艺术。

喜欢摄影,可惜穷,买不起单反,手机照片拍的不错。

懒。

被称为正太的娃。。

QQ:632975989

Gmail:[email protected]

Github

知乎

segmentfault

stackoverflow

新浪微博

人人

about.me

【译】html5游戏入门

【译】html5游戏入门

原文链接

简介

如果你想用canvas做个游戏,那么来对地方了。

但是但是你至少知道javascript怎么拼写(╯‵□′)╯︵┻━┻

既然没问题,那先来一下或者下载

创建canvas标签

废话不多说,我们必须创建一个canvas标签,简单起见,用一下不喜欢的jQuery

var CANVAS_WIDTH = 480;
var CANVAS_HEIGHT = 320;

var canvasElement = $("<canvas width='" + CANVAS_WIDTH + 
                      "' height='" + CANVAS_HEIGHT + "'></canvas>");
var canvas = canvasElement.get(0).getContext("2d");
canvasElement.appendTo('body');

游戏循环

为了能够让游戏平滑动画,我们用30帧的频率。

var FPS = 30;
setInterval(function() {
  update();
  draw();
}, 1000/FPS);

现在我们可以先给这两个函数放置play,重要的是setInterval函数会定期照顾他们的。

hello world

现在我们有了这个循环,让我们开始画东西吧~

function draw() {
  canvas.fillStyle = "#000"; // Set color to black
  canvas.fillText("Sup Bro!", 50, 50);
}

注意:确认修改之后刷新一下,万一哪里不对,代码变的少还能看出哪里不对。

The end of year 2012,and the begin of new life

I should write this post yesterday, and i return home yesterday, and sleep very early. So i do it today.

Today is december 31th, the end of year 2012, and i've seemed so many friends celebrate the New year's day, and even somebody says them want to keep sober until the time of 12:00.

And this is my first time write english post, and i don't know what to say, and seems nothing else to say, this all.

thank you.

canvas画loading图标

http://jsbin.com/okAbatU/1/edit

var c = document.getElementsByTagName('CANVAS')[0];
var ctx = c.getContext('2d');

var drawCircle = function (deg) {
    ctx.lineWidth = 6;

    for(var i = 1; i < 361; i++) {
        var red   = 255;
        var green = 124;
        var blue  = 36;
        var alpha = i / 360 ;
        ctx.beginPath();
        ctx.strokeStyle = 'rgba(' + [red, green, blue, alpha].join(',') + ')';
        ctx.arc(50, 50, 30, (i -1 + deg) * Math.PI / 180, (i + deg) * Math.PI / 180);
        ctx.stroke();
    }
};

var deg = 0,
    dis = 10;
var id = setInterval(function() {
    ctx.clearRect(0,0,100,100);
    deg += dis;
    if (deg > 360) { //完成一个圆的绘制后重新开始绘制
        deg = 0;
    }

    drawCircle(deg);
}, 1000/30);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.