<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">
<channel>
	<title>O Desenvolvedor</title>
	<link>http://andafter.org/blogs/odesenvolvedor</link>
	<pubDate>Wed, 31 Dec 1969 8:24:05 -0300</pubDate>
	<description />
	<generator>GS Solutions</generator>
	<language>pt-br</language>
	<copyright>Copyright GS Solutions - Tecnologia da Informação. Todos os direitos reservados.</copyright>
	<webMaster>contato@andafter.org</webMaster>
	<creativeCommons:license>http://creativecommons.org/licenses/by-sa/2.0/</creativeCommons:license>
	<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />

		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/ODesenvolvedor" /><feedburner:info uri="odesenvolvedor" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId>ODesenvolvedor</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><feedburner:feedFlare href="http://add.my.yahoo.com/rss?url=http%3A%2F%2Ffeeds.feedburner.com%2FODesenvolvedor" src="http://us.i1.yimg.com/us.yimg.com/i/us/my/addtomyyahoo4.gif">Subscribe with My Yahoo!</feedburner:feedFlare><feedburner:feedFlare href="http://www.newsgator.com/ngs/subscriber/subext.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2FODesenvolvedor" src="http://www.newsgator.com/images/ngsub1.gif">Subscribe with NewsGator</feedburner:feedFlare><feedburner:feedFlare href="http://feeds.my.aol.com/add.jsp?url=http%3A%2F%2Ffeeds.feedburner.com%2FODesenvolvedor" src="http://o.aolcdn.com/favorites.my.aol.com/webmaster/ffclient/webroot/locale/en-US/images/myAOLButtonSmall.gif">Subscribe with My AOL</feedburner:feedFlare><feedburner:feedFlare href="http://www.bloglines.com/sub/http://feeds.feedburner.com/ODesenvolvedor" src="http://www.bloglines.com/images/sub_modern11.gif">Subscribe with Bloglines</feedburner:feedFlare><feedburner:feedFlare href="http://www.netvibes.com/subscribe.php?url=http%3A%2F%2Ffeeds.feedburner.com%2FODesenvolvedor" src="http://www.netvibes.com/img/add2netvibes.gif">Subscribe with Netvibes</feedburner:feedFlare><feedburner:feedFlare href="http://fusion.google.com/add?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2FODesenvolvedor" src="http://buttons.googlesyndication.com/fusion/add.gif">Subscribe with Google</feedburner:feedFlare><feedburner:feedFlare href="http://www.pageflakes.com/subscribe.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2FODesenvolvedor" src="http://www.pageflakes.com/ImageFile.ashx?instanceId=Static_4&amp;fileName=ATP_blu_91x17.gif">Subscribe with Pageflakes</feedburner:feedFlare><feedburner:feedFlare href="http://www.plusmo.com/add?url=http%3A%2F%2Ffeeds.feedburner.com%2FODesenvolvedor" src="http://plusmo.com/res/graphics/fbplusmo.gif">Subscribe with Plusmo</feedburner:feedFlare><feedburner:feedFlare href="http://www.thefreedictionary.com/_/hp/AddRSS.aspx?http%3A%2F%2Ffeeds.feedburner.com%2FODesenvolvedor" src="http://img.tfd.com/hp/addToTheFreeDictionary.gif">Subscribe with The Free Dictionary</feedburner:feedFlare><feedburner:feedFlare href="http://www.bitty.com/manual/?contenttype=rssfeed&amp;contentvalue=http%3A%2F%2Ffeeds.feedburner.com%2FODesenvolvedor" src="http://www.bitty.com/img/bittychicklet_91x17.gif">Subscribe with Bitty Browser</feedburner:feedFlare><feedburner:feedFlare href="http://www.newsalloy.com/?rss=http%3A%2F%2Ffeeds.feedburner.com%2FODesenvolvedor" src="http://www.newsalloy.com/subrss3.gif">Subscribe with NewsAlloy</feedburner:feedFlare><feedburner:feedFlare href="http://www.live.com/?add=http%3A%2F%2Ffeeds.feedburner.com%2FODesenvolvedor" src="http://tkfiles.storage.msn.com/x1piYkpqHC_35nIp1gLE68-wvzLZO8iXl_JMledmJQXP-XTBOLfmQv4zhj4MhcWEJh_GtoBIiAl1Mjh-ndp9k47If7hTaFno0mxW9_i3p_5qQw">Subscribe with Live.com</feedburner:feedFlare><feedburner:feedFlare href="http://mix.excite.eu/add?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2FODesenvolvedor" src="http://image.excite.co.uk/mix/addtomix.gif">Subscribe with Excite MIX</feedburner:feedFlare><feedburner:feedFlare href="http://www.yourminis.com/subscribe.aspx?u=http%3A%2F%2Ffeeds.feedburner.com%2FODesenvolvedor" src="http://www.yourminis.com/images/addtoyourminisbadge.gif">Subscribe with Yourminis.com</feedburner:feedFlare><feedburner:feedFlare href="http://download.attensa.com/app/get_attensa.html?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2FODesenvolvedor" src="http://www.attensa.com/blogs/attensa/WindowsLiveWriter/BadgeredintoBadges_10C02/attensa_feed_button5.gif">Subscribe with Attensa for Outlook</feedburner:feedFlare><feedburner:feedFlare href="http://www.webwag.com/wwgthis.php?url=http%3A%2F%2Ffeeds.feedburner.com%2FODesenvolvedor" src="http://www.webwag.com/images/wwgthis.gif">Subscribe with Webwag</feedburner:feedFlare><feedburner:feedFlare href="http://hub.netomat.net/account/account.autoSubscribe.jspa?urls=http%3A%2F%2Ffeeds.feedburner.com%2FODesenvolvedor" src="http://www.netomat.net/blogger/images/icon_netomat_feedbutton.gif">Subscribe with netomat Hub</feedburner:feedFlare><feedburner:feedFlare href="http://www.podcastready.com/oneclick_bookmark.php?url=http%3A%2F%2Ffeeds.feedburner.com%2FODesenvolvedor" src="http://www.podcastready.com/images/podcastready_button.gif">Subscribe with Podcast Ready</feedburner:feedFlare><feedburner:feedFlare href="http://www.flurry.com/pushRssFeed.do?r=fb&amp;url=http%3A%2F%2Ffeeds.feedburner.com%2FODesenvolvedor" src="http://www.flurry.com/images/flurry_rss_logo2.gif">Subscribe with Flurry</feedburner:feedFlare><feedburner:feedFlare href="http://www.wikio.com/subscribe?url=http%3A%2F%2Ffeeds.feedburner.com%2FODesenvolvedor" src="http://www.wikio.com/shared/img/add2wikio.gif">Subscribe with Wikio</feedburner:feedFlare><feedburner:feedFlare href="http://www.dailyrotation.com/index.php?feed=http%3A%2F%2Ffeeds.feedburner.com%2FODesenvolvedor" src="http://www.dailyrotation.com/rss-dr2.gif">Subscribe with Daily Rotation</feedburner:feedFlare><item>
		<title>Pong em HTML5 Canvas</title>
		<link>http://feedproxy.google.com/~r/ODesenvolvedor/~3/72mB1heKQqY/pong-em-html5-canvas.html</link>
		<comments>http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/pong-em-html5-canvas.html#comment</comments>
		<pubDate>Wed, 31 Dec 1969 8:24:05 -0300</pubDate>
		<dc:creator>And After - Guilherme Serrano</dc:creator>
	<dc:subject>html5</dc:subject><dc:subject>canvas</dc:subject><dc:subject>front-end</dc:subject><dc:subject>open-web</dc:subject><dc:subject>javascript</dc:subject>
		<guid isPermaLink="false">http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/pong-em-html5-canvas.html</guid>
		<description><![CDATA[Estudo de canvas aplicado em games, como fazer um pong com HTML5?]]></description>
		<content:encoded><![CDATA[<p>
	Recentemente eu escrevi um <strong><a href="http://odesenvolvedor.andafter.org/publicacoes/html5-canvas-tutorial-para-iniciantes.html" title="Tutorial de Canvas">turorial de Canvas (HTML5) para iniciantes</a></strong>, que comecei a escrever para aprender <strong>Canvas</strong>.</p>
<p>
	Comecei a buscar formas divertidas de aprender canvas e como <strong>games em HTML5</strong> me chamaram a aten&ccedil;&atilde;o desde a primeira vez que li sobre o assunto, porque n&atilde;o aprender canvas desenvolvendo algum game? <strong>:)</strong></p>
<p>
	&Eacute; tamb&eacute;m uma forma de mostrar o que &eacute; poss&iacute;vel com <a href="/tag/html5"><strong>HTML5</strong></a> e expandir as id&eacute;ias para as aplica&ccedil;&otilde;es que podem ser feitas com um pouco de criatividade.</p>
<h2>
	<strong>Pong em Canvas</strong></h2>
<p>
	Vou explicar o desenvolvimento do <strong><a href="http://andafter.org/labs/home/pong" title="HTML5 Pong">Pong em HTML5</a></strong>.</p>
<p>
	Para facilitar a manuten&ccedil;&atilde;o procurei desenvolver todo o game com <a href="http://odesenvolvedor.andafter.org/publicacoes/jogo-de-dados-javascript-orientado-a-objetos_1150.html" title="Javascript orientado a objetos"><strong>orienta&ccedil;&atilde;o a objetos</strong></a> em quase tudo, ent&atilde;o recomendo leitura sobre o assunto caso voc&ecirc; n&atilde;o se sinta confort&aacute;vel com esse tipo de c&oacute;digo.</p>
<p>
	O primeiro passo &eacute; criar a estrutura do game:</p>
<p>
	function Pong(){<br />
	&nbsp; &nbsp; _this = this;<br />
	}</p>
<p>
	Todo o game &eacute; estruturado em basicamente 2 objetos de dados e algumas fun&ccedil;&otilde;es (m&eacute;todos) auxiliares que fazem a manipula&ccedil;&atilde;o dos dados, anima&ccedil;&atilde;o e regras do jogo.</p>
<p>
	&nbsp;</p>
<h3>
	Os objetos do game</h3>
<h4>
	<strong>Players</strong></h4>
<p>
	Cada player &eacute; um objeto onde &eacute; armazenado as informa&ccedil;&otilde;es do jogador, como pontua&ccedil;&atilde;o, id, localiza&ccedil;&atilde;o do seu &quot;pad&quot; e regra de movimenta&ccedil;&atilde;o (se ele deve ir para a direita ou esquerda).</p>
<p class="p1">
	this.player = function(){</p>
<p class="p1">
	&nbsp; &nbsp; this.score = 0,<br />
	&nbsp; &nbsp; this.left = false,<br />
	&nbsp; &nbsp; this.right = false;&nbsp; &nbsp;&nbsp;</p>
<p class="p1">
	&nbsp; &nbsp; this.paddle = {<br />
	&nbsp; &nbsp; &nbsp; &nbsp; x : 0,<br />
	&nbsp; &nbsp; &nbsp; &nbsp; y : (_this.HEIGHT / 2)-60,<br />
	&nbsp; &nbsp; &nbsp; &nbsp; w : 7,<br />
	&nbsp; &nbsp; &nbsp; &nbsp; h : 120<br />
	&nbsp; &nbsp; };</p>
<p class="p1">
	}</p>
<p>
	&nbsp;</p>
<p>
	&nbsp;</p>
<h4>
	<strong>Bola</strong></h4>
<p>
	A bola &eacute; outro objeto do game, nela ficam armazenados sua posi&ccedil;&atilde;o (x,y) e o raio utilizado para o desenho.</p>
<p class="p1" style="margin-left: 40px; ">
	this.bola = {<br />
	&nbsp; &nbsp; &nbsp; x : 8,<br />
	&nbsp; &nbsp; &nbsp; y : 50,<br />
	&nbsp; &nbsp; &nbsp; r : 6<br />
	}</p>
<h2>
	&nbsp;</h2>
<h2>
	M&eacute;todos do Pong</h2>
<p>
	Estruturei uma s&eacute;rie de fun&ccedil;&otilde;es para facilitar o desenho e aplica&ccedil;&atilde;o das regras do game. Acredito que o c&oacute;digo ficou bastante leg&iacute;vel e voc&ecirc; pode ler ele <a href="http://andafter.org/labs/home/pong" title="Pong em HTML5"><strong>diretamente no game</strong></a>.</p>
<p>
	&nbsp;</p>
<h3>
	init()</h3>
<p>
	Chamada no in&iacute;cio do jogo esta fun&ccedil;&atilde;o define o contexto do canvas, os valores iniciais dos objetos (players, bola) e armazena tamb&eacute;m o tamanho do canvas, &eacute; utilizado para posicionar os pads e a bola. A fun&ccedil;&atilde;o tamb&eacute;m cria os 2 jogadores e posiciona seus &quot;pads&quot; no local correto.</p>
<p>
	As vari&aacute;veis &quot;wind&quot; e &quot;gravity&quot; s&atilde;o as duas for&ccedil;as que atuam na bola (horizontal e verticalmente).</p>
<p>
	&nbsp;</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.init = function(selector){</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.ctx = $(&quot;#canvas&quot;)[0].getContext(&quot;2d&quot;),</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.WIDTH = $(&quot;#canvas&quot;)[0].width,</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.HEIGHT = $(&quot;#canvas&quot;)[0].height,</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.gravity = 4,</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.wind = 10,</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.p1 = new _this.player(),</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.p1.id = 1,</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.p2 = new _this.player(),</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.p2.id = 2,</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.p2.paddle.x = (_this.WIDTH-7);</p>
<p class="p2">
	&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(document).keydown(_this.onKeyDown);</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(document).keyup(_this.onKeyUp);</p>
<p class="p2">
	&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }</p>
<p class="p1">
	&nbsp;</p>
<p class="p1">
	&nbsp;</p>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&nbsp;</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	_this.ctx = $(&quot;#canvas&quot;)[0].getContext(&quot;2d&quot;),</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&nbsp;</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	_this.WIDTH = $(&quot;#canvas&quot;)[0].width,</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&nbsp;</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	_this.HEIGHT = $(&quot;#canvas&quot;)[0].height,</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&nbsp;</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	_this.gravity = 4,</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&nbsp;</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	_this.wind = 10,</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&nbsp;</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	_this.p1 = new _this.player(),</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&nbsp;</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	_this.p1.id = 1,</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&nbsp;</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	_this.p2 = new _this.player(),</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&nbsp;</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	_this.p2.id = 2,</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&nbsp;</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	_this.p2.paddle.x = (_this.WIDTH-7);</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&nbsp;</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&nbsp;</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&nbsp;</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	$(document).keydown(_this.onKeyDown);</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&nbsp;</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 837px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	$(document).keyup(_this.onKe</div>
<h3>
	Fun&ccedil;&otilde;es de desenho</h3>
<p class="p1">
	Os m&eacute;todos circle, rect e clean s&atilde;o apenas atalhos para os <strong><a href="http://odesenvolvedor.andafter.org/publicacoes/html5-canvas-tutorial-para-iniciantes.html" title="Tutorial de Canvas">m&eacute;todos de desenho do Canvas</a></strong>, utilizados para a cada frame redesenhar a bola e os pads em suas novas posi&ccedil;&otilde;es.</p>
<p class="p1">
	&nbsp;</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.circle = function(x,y,r){</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.ctx.fillStyle = &quot;rgba(0,0,255,.9)&quot;;</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.ctx.beginPath();</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.ctx.arc(x, y, r, 0, Math.PI*2, true);</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.ctx.closePath();</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.ctx.fill();</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }</p>
<p class="p2">
	&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.rect = function(x,y,w,h){</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.ctx.fillStyle = &quot;rgba(255,0,0,.6)&quot;;</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.ctx.beginPath();</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.ctx.rect(x,y,w,h);</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.ctx.closePath();</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.ctx.fill();</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }</p>
<p class="p2">
	&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.clear = function(){</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.ctx.clearRect(0, 0, _this.WIDTH,_this.HEIGHT);</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }</p>
<p>
	&nbsp;</p>
<p>
	&nbsp;</p>
<h2>
	Intera&ccedil;&atilde;o com teclado</h2>
<p>
	Como fazer um objeto se movimentar no canvas utilizando o teclado? Na fun&ccedil;&atilde;o init do game defini que a a&ccedil;&atilde;o &quot;keyup&quot; e &quot;keydown&quot; do jQuery iriam disparar um m&eacute;todo do game.&nbsp;</p>
<p>
	A cada a&ccedil;&atilde;o de Keydown &eacute; feito uma verifica&ccedil;&atilde;o de qual tecla foi pressionada. Se a tecla pressionada foi a direcional esquerda ou a direcional direita (veja a <a href="http://odesenvolvedor.andafter.org/publicacoes/tabela-de-key-codes-para-javascript_1464.html" title="Tabela de keycode para javascript"><strong>tabela de keycodes para javascript</strong></a>) o objeto do player 1 &eacute; alterado, modificando a flag &quot;left&quot; ou a flag &quot;right&quot; para true.</p>
<p>
	O Keydown faz a a&ccedil;&atilde;o inversa, tornando as flags &quot;false&quot; dependendo de qual tecla foi liberada do teclado.</p>
<p>
	&nbsp;</p>
<p>
	&nbsp;</p>
<p class="p1">
	_this.onKeyDown = function(evt) {</p>
<p class="p1">
	&nbsp; &nbsp; switch(evt.keyCode){</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; /* seta direita */</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; case 39:</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.p1.right = true;</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; /* seta esquerda */</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; case 37:</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.p1.left = true;</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; /* espaco */</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; case 32:</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.play();</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;</p>
<p class="p1">
	&nbsp; &nbsp; }</p>
<p class="p2">
	&nbsp;&nbsp;</p>
<p class="p1">
	}</p>
<p class="p2">
	&nbsp;</p>
<p class="p1">
	/* Keyup events */</p>
<p class="p1">
	_this.onKeyUp = function(evt) {</p>
<p class="p1">
	&nbsp; &nbsp; switch(evt.keyCode){</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; /* seta direita */</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; case 39:</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.p1.right = false;</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; /* seta esquerda */</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; case 37:</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.p1.left = false;</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;</p>
<p class="p1">
	&nbsp; &nbsp; }</p>
<p class="p1">
	}</p>
<p>
	&nbsp;</p>
<p>
	&nbsp;</p>
<p>
	&nbsp;</p>
<h3>
	As regras e anima&ccedil;&atilde;o do jogo</h3>
<p>
	Neste ponto n&oacute;s j&aacute; temos os objetos e players, bola, e todas as informa&ccedil;&otilde;es do canvas e for&ccedil;as que v&atilde;o atuar no nosso jogo. Tamb&eacute;m temos os controles configurados, ao pressionar as teclas nosso objeto player &eacute; alterado.</p>
<p>
	Agora precisamos &quot;dar vida&quot; ao game, para isso iremos redesenhar o nosso canvas a cada 25 milisegundos. Primeiro vamos a l&oacute;gica:</p>
<p>
	A cada 25 milisegundos iremos:</p>
<ol>
	<li>
		Calcular e desenhar a bola em sua nova posi&ccedil;&atilde;o (de acordo com os valores de wind e gravity, que s&atilde;o as for&ccedil;as que atuam na bolinha)</li>
	<li>
		Verificar se o pad do player 1 deve ir para cima ou para baixo (vari&aacute;veis left e right indicando que as teclas est&atilde;o pressionadas)
		<ol>
			<li>
				Em caso positivo, desenhar o pad na nova posi&ccedil;&atilde;o</li>
		</ol>
	</li>
	<li>
		Se a bolinha bater em cima ou em baixo do canvas, inverter o valor de &quot;gravity&quot; para que a bolinha continue dentro do nosso canvas</li>
	<li>
		Verificar se &eacute; gol (se a bola acertou a lateral esquerda ou direita do canvas sem atingir os pads)</li>
</ol>
<p>
	&nbsp;</p>
<p>
	Estas s&atilde;o as regras do game convertidas para &quot;bom portugu&ecirc;s&quot;, agora vamos para o c&oacute;digo:</p>
<p>
	&nbsp;</p>
<p class="p1">
	this.animate = function (){</p>
<p class="p1">
	&nbsp; &nbsp; /* limpa e redesenha a bola */</p>
<p class="p1">
	&nbsp; &nbsp; _this.clear();</p>
<p class="p1">
	&nbsp; &nbsp; _this.circle(_this.bola.x,_this.bola.y,_this.bola.r);</p>
<p class="p2">
	&nbsp;&nbsp; &nbsp;</p>
<p class="p1">
	&nbsp; &nbsp; var speed = 8;</p>
<p class="p2">
	&nbsp;&nbsp; &nbsp;</p>
<p class="p1">
	&nbsp; &nbsp; /* player 1 */</p>
<p class="p1">
	&nbsp; &nbsp; if (_this.p1.right &amp;&amp; _this.p1.paddle.y &lt; (_this.HEIGHT - _this.p1.paddle.h)) _this.p1.paddle.y += speed;</p>
<p class="p1">
	&nbsp; &nbsp; else if (_this.p1.left &amp;&amp; _this.p1.paddle.y &gt; 0) _this.p1.paddle.y -= speed;</p>
<p class="p1">
	&nbsp; &nbsp; _this.rect(_this.p1.paddle.x,_this.p1.paddle.y,_this.p1.paddle.w,_this.p1.paddle.h);</p>
<p class="p2">
	&nbsp;&nbsp; &nbsp;</p>
<p class="p1">
	&nbsp; &nbsp; /* saida lateral */</p>
<p class="p1">
	&nbsp; &nbsp; if (_this.bola.y + _this.gravity &gt; _this.HEIGHT || _this.bola.y + _this.gravity &lt; 0){</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; _this.gravity = -_this.gravity;</p>
<p class="p1">
	&nbsp; &nbsp; }</p>
<p class="p2">
	&nbsp;&nbsp; &nbsp;</p>
<p class="p1">
	&nbsp; &nbsp; if(_this.bola.x + _this.wind&gt; _this.WIDTH){</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; if(_this.bola.y &gt; _this.p2.paddle.y &amp;&amp; _this.bola.y &lt; (_this.p2.paddle.y + _this.p2.paddle.h)){</p>
<p class="p1">
	&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.wind = -_this.wind;</p>
<p class="p1">
	&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.gravity = _this.randomize();</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; }else{</p>
<p class="p1">
	&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.p1.score++;</p>
<p class="p1">
	&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(&#39;#score-1&#39;).html(_this.p1.score);</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.bola.x = (_this.WIDTH / 2),</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.bola.y = (_this.HEIGHT / 2);</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.wind = -_this.wind;</p>
<p class="p1">
	&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.play();</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; }</p>
<p class="p1">
	&nbsp; &nbsp; }else if(_this.bola.x + _this.wind &lt; 0){</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; if(_this.bola.y &gt; _this.p1.paddle.y &amp;&amp; _this.bola.y &lt; (_this.p1.paddle.y + _this.p1.paddle.h)){</p>
<p class="p1">
	&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.wind = -_this.wind;</p>
<p class="p1">
	&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.gravity = _this.randomize();</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; }else{</p>
<p class="p1">
	&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.p2.score++;</p>
<p class="p1">
	&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(&#39;#score-2&#39;).html(_this.p2.score);</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.bola.x = (_this.WIDTH / 2),</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.bola.y = (_this.HEIGHT / 2);</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.wind = -_this.wind;</p>
<p class="p1">
	&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.play();</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; }</p>
<p class="p1">
	&nbsp; &nbsp; }</p>
<p class="p2">
	&nbsp;&nbsp; &nbsp;</p>
<p class="p2">
	&nbsp;&nbsp; &nbsp;</p>
<p class="p1">
	&nbsp; &nbsp; _this.bola.y += _this.gravity;</p>
<p class="p1">
	&nbsp; &nbsp; _this.bola.x += _this.wind;</p>
<p class="p1">
	}</p>
<p>
	&nbsp;</p>
<p>
	O c&oacute;digo acima tamb&eacute;m j&aacute; est&aacute; marcando a pontua&ccedil;&atilde;o e manipulando o HTML para exibi&ccedil;&atilde;o dos pontos. Retirei a parte do player 2 para facilitar, ele &eacute; um bot e est&aacute; explicado abaixo:</p>
<p>
	&nbsp;</p>
<h2>
	Player 2 (NPC)</h2>
<p>
	Ainda n&atilde;o trabalhei muito no bot, estava ansioso para compartilhar e colocar o <a href="http://andafter.org/labs/home/pong"><strong>Pong</strong></a> no ar e n&atilde;o consegui deixar exatamente como eu gostaria. Ele &quot;persegue&quot; a bolinha a partir de certo ponto da nossa quadra (do elemento canvas).</p>
<p>
	&nbsp;</p>
<p class="p1">
	&nbsp; &nbsp; /* bot */</p>
<p class="p1">
	&nbsp; &nbsp; var delay = 300;</p>
<p class="p1">
	&nbsp; &nbsp; if(_this.bola.y &lt; (_this.p2.paddle.y + (_this.p2.paddle.h / 3)) &amp; _this.p2.paddle.y &gt; 0 &amp;&amp; _this.bola.x &gt; delay){</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; _this.p2.paddle.y -= speed;</p>
<p class="p1">
	&nbsp; &nbsp; }else if(_this.bola.y &gt; (_this.p2.paddle.y - (_this.p2.paddle.h / 3)) &amp;&amp; _this.p2.paddle.y &lt; (_this.HEIGHT - _this.p2.paddle.h) &amp;&amp; _this.bola.x &gt; delay){</p>
<p class="p1">
	&nbsp; &nbsp; &nbsp; &nbsp; _this.p2.paddle.y += speed;</p>
<p class="p1">
	&nbsp; &nbsp; }</p>
<p class="p1">
	&nbsp; &nbsp; _this.rect(_this.p2.paddle.x,_this.p2.paddle.y,_this.p2.paddle.w,_this.p2.paddle.h);</p>
<p>
	&nbsp;</p>
<p>
	&nbsp;</p>
<p>
	Espero que este post desperte curiosidade e id&eacute;ias! Sugest&otilde;es, cr&iacute;ticas e d&uacute;vidas nos coment&aacute;rios.</p>
<img src="http://feeds.feedburner.com/~r/ODesenvolvedor/~4/72mB1heKQqY" height="1" width="1"/>]]></content:encoded>
		<feedburner:origLink>http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/pong-em-html5-canvas.html</feedburner:origLink></item>
	
		<item>
		<title>HTML5 Canvas - Tutorial para iniciantes</title>
		<link>http://feedproxy.google.com/~r/ODesenvolvedor/~3/VSvkJIgeVKw/html5-canvas-tutorial-para-iniciantes.html</link>
		<comments>http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/html5-canvas-tutorial-para-iniciantes.html#comment</comments>
		<pubDate>Wed, 31 Dec 1969 10:21:04 -0300</pubDate>
		<dc:creator>And After - Guilherme Serrano</dc:creator>
	<dc:subject>html5</dc:subject><dc:subject>canvas</dc:subject><dc:subject>front-end</dc:subject><dc:subject>open-web</dc:subject>
		<guid isPermaLink="false">http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/html5-canvas-tutorial-para-iniciantes.html</guid>
		<description><![CDATA[Tutorial para quem está começando a aprender Canvas (HTML5) ou quer relembrar os princípios básicos do Canvas.]]></description>
		<content:encoded><![CDATA[<h2>
	O que &eacute; Canvas HTML5?</h2>
<p>
	&nbsp;<a href="" title="Mais posts sobre HTML5">HTML5</a>&nbsp;trouxe diversas novas tags, al&eacute;m das <a href="http://odesenvolvedor.andafter.org/publicacoes/formularios-em-html5-novos-tipos-de-input_1897.html" title="Novas tags de input (formulario) do HTML5">novidades nas tags input de formul&aacute;rio</a> e das tags sem&acirc;nticas como <a href="http://odesenvolvedor.andafter.org/publicacoes/html5-section-ou-article_1893.html" title="Article ou section?"><strong>article e section</strong></a>, uma das grandes mudan&ccedil;as implementadas foi a tag canvas.</p>
<p>
	Canvas &eacute; uma nova tag que permite&nbsp;voc&ecirc; trabalhar e manipular elementos gr&aacute;ficos (raster). A tag canvas &eacute; um &quot;board&quot; de desenho no HTML, nele voc&ecirc; pode desenhar linhas, elementos, manipular pixel a pixel, carregar e manipular imagens externas (rotacionar, alterar cor, brilho, etc.).</p>
<p>
	&Eacute; uma evolu&ccedil;&atilde;o gigante pois permite a manipula&ccedil;&atilde;o em tempo real do que est&aacute; sendo impresso como imagem no computador do cliente.</p>
<p>
	Um exemplo de uso s&atilde;o jogos, gr&aacute;ficos e interfaces ainda mais interativas.</p>
<p>
	&nbsp;</p>
<h2>
	Quais navegadores d&atilde;o suporte ao Canvas?</h2>
<p>
	Praticamente todos os navegadores modernos d&atilde;o suporte ao Canvas. Confira a tabela abaixo:</p>
<p>
	&nbsp;</p>
<table class="main" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; border-collapse: collapse; color: rgb(61, 53, 39); font-family: Verdana, Arial, sans-serif; font-size: 14px; width: 640px; ">
	<thead>
		<tr style="margin-bottom: 2px; border-top-right-radius: 5px; ">
			<th class="first" style="background-color: initial; padding-top: 0.1em; padding-right: 0.1em; padding-bottom: 0.1em; padding-left: 0.1em; color: white; min-width: 3em; box-shadow: none; -webkit-box-shadow: none; background-image: -webkit-gradient(linear, 0% 0%, 100% 0%, from(rgb(218, 200, 167)), color-stop(0.5, rgb(207, 183, 139)), to(rgb(207, 183, 139))); background-attachment: initial; background-origin: initial; background-clip: initial; font-family: AurulentSansRegular, serif !important; border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; border-top-color: rgb(218, 200, 167); border-right-color: rgb(218, 200, 167); border-bottom-color: rgb(218, 200, 167); border-left-color: rgb(218, 200, 167); text-align: left; width: 9em; font-size: 13px; ">
				&nbsp;</th>
			<th class="ie" style="background-color: rgb(35, 61, 97); padding-top: 0.1em; padding-right: 0.1em; padding-bottom: 0.1em; padding-left: 0.1em; color: white; min-width: 3em; box-shadow: rgba(255, 255, 255, 0.199219) 0px 5px 8px inset; -webkit-box-shadow: rgba(255, 255, 255, 0.199219) 0px 5px 8px inset; border-top-left-radius: 5px; ">
				IE</th>
			<th class="firefox" style="background-color: rgb(163, 98, 35); padding-top: 0.1em; padding-right: 0.1em; padding-bottom: 0.1em; padding-left: 0.1em; color: white; min-width: 3em; box-shadow: rgba(255, 255, 255, 0.199219) 0px 5px 8px inset; -webkit-box-shadow: rgba(255, 255, 255, 0.199219) 0px 5px 8px inset; ">
				Firefox</th>
			<th class="chrome" style="background-color: rgb(63, 119, 187); padding-top: 0.1em; padding-right: 0.1em; padding-bottom: 0.1em; padding-left: 0.1em; color: white; min-width: 3em; box-shadow: rgba(255, 255, 255, 0.199219) 0px 5px 8px inset; -webkit-box-shadow: rgba(255, 255, 255, 0.199219) 0px 5px 8px inset; ">
				Chrome</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<th>
				14 versions back</th>
			<td title="Unknown">
				&nbsp;</td>
			<td title="Unknown">
				&nbsp;</td>
			<td class="y" title="Supported">
				4.0<span class="res">: Supported</span></td>
		</tr>
		<tr>
			<th>
				13 versions back</th>
			<td title="Unknown">
				&nbsp;</td>
			<td title="Unknown">
				&nbsp;</td>
			<td class="y" title="Supported">
				5.0<span class="res">: Supported</span></td>
		</tr>
		<tr>
			<th>
				12 versions back</th>
			<td title="Unknown">
				&nbsp;</td>
			<td class="y" title="Supported">
				2.0<span class="res">: Supported</span></td>
			<td class="y" title="Supported">
				6.0<span class="res">: Supported</span></td>
		</tr>
		<tr>
			<th>
				11 versions back</th>
			<td title="Unknown">
				&nbsp;</td>
			<td class="y" title="Supported">
				3.0<span class="res">: Supported</span></td>
			<td class="y" title="Supported">
				7.0<span class="res">: Supported</span></td>
		</tr>
		<tr>
			<th>
				10 versions back</th>
			<td title="Unknown">
				&nbsp;</td>
			<td class="y" title="Supported">
				3.5<span class="res">: Supported</span></td>
			<td class="y" title="Supported">
				8.0<span class="res">: Supported</span></td>
		</tr>
		<tr>
			<th>
				9 versions back</th>
			<td title="Unknown">
				&nbsp;</td>
			<td class="y" title="Supported">
				3.6<span class="res">: Supported</span></td>
			<td class="y" title="Supported">
				9.0<span class="res">: Supported</span></td>
		</tr>
		<tr>
			<th>
				8 versions back</th>
			<td title="Unknown">
				&nbsp;</td>
			<td class="y" title="Supported">
				4.0<span class="res">: Supported</span></td>
			<td class="y" title="Supported">
				10.0<span class="res">: Supported</span></td>
		</tr>
		<tr>
			<th>
				7 versions back</th>
			<td title="Unknown">
				&nbsp;</td>
			<td class="y" title="Supported">
				5.0<span class="res">: Supported</span></td>
			<td class="y" title="Supported">
				11.0<span class="res">: Supported</span></td>
		</tr>
		<tr>
			<th>
				6 versions back</th>
			<td title="Unknown">
				&nbsp;</td>
			<td class="y" title="Supported">
				6.0<span class="res">: Supported</span></td>
			<td class="y" title="Supported">
				12.0<span class="res">: Supported</span></td>
		</tr>
		<tr>
			<th>
				5 versions back</th>
			<td title="Unknown">
				&nbsp;</td>
			<td class="y" title="Supported">
				7.0<span class="res">: Supported</span></td>
			<td class="y" title="Supported">
				13.0<span class="res">: Supported</span></td>
		</tr>
		<tr>
			<th>
				4 versions back</th>
			<td class="n" title="Not supported">
				5.5<span class="res">: Not supported</span></td>
			<td class="y" title="Supported">
				8.0<span class="res">: Supported</span></td>
			<td class="y" title="Supported">
				14.0<span class="res">: Supported</span></td>
		</tr>
		<tr>
			<th>
				3 versions back</th>
			<td class="p" title="Not supported (but has polyfill available)">
				6.0<span class="res">: Not supported (but has polyfill available)</span></td>
			<td class="y" title="Supported">
				9.0<span class="res">: Supported</span></td>
			<td class="y" title="Supported">
				15.0<span class="res">: Supported</span></td>
		</tr>
		<tr>
			<th>
				2 versions back</th>
			<td class="p" title="Not supported (but has polyfill available)">
				7.0<span class="res">: Not supported (but has polyfill available)</span></td>
			<td class="y" title="Supported">
				10.0<span class="res">: Supported</span></td>
			<td class="y" title="Supported">
				16.0<span class="res">: Supported</span></td>
		</tr>
		<tr>
			<th>
				Previous version</th>
			<td class="p" title="Not supported (but has polyfill available)">
				8.0<span class="res">: Not supported (but has polyfill available)</span></td>
			<td class="y" title="Supported">
				11.0<span class="res">: Supported</span></td>
			<td class="y" title="Supported">
				17.0<span class="res">: Supported</span></td>
			<td class="y" title="Supported">
				3.0<span class="res">: Supported</span></td>
		</tr>
		<tr class="now">
			<th>
				Current</th>
			<td class="y" title="Supported">
				9.0<span class="res">: Supported</span></td>
			<td class="y" title="Supported">
				12.0<span class="res">: Supported</span></td>
			<td class="y" title="Supported">
				18.0<span class="res">: Supported</span></td>
		</tr>
		<tr>
			<th>
				Near future</th>
			<td class="y" title="Supported">
				10.0<span class="res">: Supported</span></td>
			<td class="y" title="Supported">
				13.0<span class="res">: Supported</span></td>
			<td class="y" title="Supported">
				19.0<span class="res">: Supported</span></td>
		</tr>
		<tr>
			<th>
				Farther future</th>
			<td title="Unknown">
				&nbsp;</td>
			<td class="y" title="Supported">
				14.0<span class="res">: Supported</span></td>
			<td class="y" title="Supported">
				20.0<span class="res">: Supported</span></td>
		</tr>
	</tbody>
</table>
<p>
	Veja a <a href="http://caniuse.com/canvas" title="Tabela de compatibilidade dos navegadores com Canvas">tabela completa e atualizada no Can I Use</a></p>
<h2>
	&nbsp;</h2>
<h2>
	Entendendo melhor o canvas</h2>
<p>
	Neste tutorial inicial vou explicar alguns m&eacute;todos do canvas e seu funcionamento. O elemento canvas &eacute; todo manipulado por javascript, e trabalha com contextos. Pelo javascript voc&ecirc; ter&aacute; acesso a diversos m&eacute;todos para desenhar nesta tela, no contexto 2D voc&ecirc; utiliza um plano cartesiano (x e y) para definir a posi&ccedil;&atilde;o de onde vai trabalhar, e atrav&eacute;s de m&eacute;todos espec&iacute;ficos pode tra&ccedil;ar formas, linhas e definir tamanhos e cores utilizadas.</p>
<p>
	Para fazer uma anima&ccedil;&atilde;o por exemplo, voc&ecirc; faz o seu primeiro desenho e atrav&eacute;s do javascript define um time que ir&aacute; limpar o seu contexto e redesenhar os objetos em sua nova posi&ccedil;&atilde;o. Isso tamb&eacute;m server para jogos em HTML5 ou intera&ccedil;&atilde;o com o usu&aacute;rio: quando acontecer a intera&ccedil;&atilde;ovoc&ecirc; limpa o contexto e redesenha sua cena com os objetos manipulados em suas novas posi&ccedil;&otilde;es.</p>
<p>
	&nbsp;</p>
<p>
	Vamos a pr&aacute;tica!</p>
<h2>
	Programando para Canvas</h2>
<p>
	Coloque o elemento canvas no seu HTML e use um identificador para facilitar a manipula&ccedil;&atilde;o do javascript.</p>
<p>
	<code>&lt;canvas id=&quot;myCanvas&quot;&gt;&lt;/canvas&gt;</code></p>
<p>
	&nbsp;</p>
<p>
	Vamos agora selecionar o nosso canvas e definir o contexto em que iremos trabalhar, aqui j&aacute; entra o javascript:</p>
<p>
	<code>window.onload = function() {<br />
	&nbsp; var canvas = document.getElementById(&quot;myCanvas&quot;);<br />
	&nbsp; var context = canvas.getContext(&quot;2d&quot;);<br />
	}; </code></p>
<p>
	&nbsp;</p>
<p>
	Isso defina que vamos trabalhar com o contexto 2D do canvas.</p>
<p>
	&nbsp;</p>
<h3>
	Desenhando uma linha com Canvas</h3>
<p>
	Agora que voc&ecirc; j&aacute; tem o seu contexto definido, vamos desenhar uma linha no nosso gr&aacute;fico, no javascript:</p>
<p>
	<code>var canvas = document.getElementById(&quot;myCanvas&quot;);<br />
	var context = canvas.getContext(&quot;2d&quot;);<br />
	context.beginPath();<br />
	context.moveTo(100, 150); //define o ponto inicial do desenho<br />
	context.lineTo(450, 50); //define a posi&ccedil;&atilde;o de in<br />
	context.lineWidth = 5; // define a largura da linha<br />
	context.strokeStyle = &quot;#ff0000&quot;; //define a cor da linha<br />
	context.stroke(); </code></p>
<p>
	&nbsp;</p>
<p>
	Pronto, temos uma linha que come&ccedil;a no ponto (100,150) e vai at&eacute; (450,50).</p>
<h3>
	Desenhando um ret&acirc;ngulo com canvas</h3>
<p>
	Agora vamos desenhar um ret&acirc;ngulo em nosso canvas, para isso no javascript temos o m&eacute;todo rect, que funciona da seguinte forma:</p>
<p>
	<code>context.rect(x, y, width, height);</code></p>
<p>
	O exemplo do c&oacute;digo completo:</p>
<p>
	<code>var canvas = document.getElementById(&#39;myCanvas&#39;);<br />
	var context = canvas.getContext(&#39;2d&#39;);<br />
	context.beginPath();<br />
	context.rect(188, 50, 200, 100); // desenha o ret&acirc;ngulo<br />
	context.fillStyle = &#39;#8ED6FF&#39;; // define o preenchimento do ret&acirc;ngulo<br />
	context.fill(); // Preenche o ret&acirc;ngulo<br />
	context.lineWidth = 5; // define a largura da linha do contorno<br />
	context.strokeStyle = &#39;black&#39;; // define a cor do contorno<br />
	context.stroke(); // desenha o contorno</code></p>
<p>
	&nbsp;</p>
<h3>
	Desenhando um c&iacute;rculo com canvas</h3>
<p>
	Para desenhar c&iacute;rculos (e arcos) temos o m&eacute;todo arc, que funciona da seguinte forma:</p>
<p>
	<code>context.arc(x, y, radius, startAngle, endAngle, antiClockwise);</code></p>
<p>
	No exemplo acima podemos desenhar arco com qualquer angulo de in&iacute;cio e fim, para desenhar c&iacute;rculos completos podemos usar o seguinte:</p>
<p>
	<code>context.arc(x, y, radius, 0 , 2 * Math.PI, false);</code></p>
<p>
	Fica mais f&aacute;cil e temos que nos preocupar apenas com o ponto cartesiano (x,y) e com o tamanho do raio do c&iacute;rculo. Abaixo um exemplo completo:</p>
<p>
	<code>var canvas = document.getElementById(&quot;myCanvas&quot;);<br />
	var context = canvas.getContext(&quot;2d&quot;);<br />
	var centerX = canvas.width / 2; // pega o centro do canvas (x)<br />
	var centerY = canvas.height / 2;&nbsp;&nbsp;// pega o centro do canvas (y)<br />
	var radius = 70;&nbsp;<br />
	<br />
	context.beginPath();<br />
	context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false); // desenha o c&iacute;rculo no centro do canvas com raio = 70<br />
	context.fillStyle = &quot;#8ED6FF&quot;; // define a cor de preenchimento<br />
	context.fill(); // desenha o preenchimento<br />
	context.lineWidth = 5; // define a expessura da borda<br />
	context.strokeStyle = &quot;black&quot;; // define a cor da borda<br />
	context.stroke(); // desenha a borda</code></p>
<p>
	&nbsp;</p>
<p>
	Esse &eacute; um tutorial introdut&oacute;rio ao Canvas, ele parece mais complicado do que realmente &eacute;. Para entender um pouco melhor o funcionamento do canvas e suas anima&ccedil;&otilde;es criei um <a href="http://andafter.org/labs/home/pong" title="Pong em HTML5 - Canvas">Pong em HTML5 Canvas</a>, mas ainda n&atilde;o tive tempo de finalizar. O c&oacute;digo est&aacute; com a leitura f&aacute;cil, vale a pena a leitura. ;)</p>
<p>
	&nbsp;</p>
<p>
	Recomendo a leitura (em ingl&ecirc;s) do <a href="http://www.html5canvastutorials.com/tutorials/">html5 canvas tutorials</a>, de onde os exemplos deste post foram retirados.</p>
<p>
	&nbsp;</p>
<p>
	Este post te ajudou de alguma forma? Retribua, divulgue o link deste artigo em seu blog, twitter ou facebook e nos ajude a <a href="http://andafter.org/publicacoes/compartilhar-conhecimento.html" title="Compartilhar conhecimento"><strong>compartilhar conhecimento</strong></a>.</p>
<img src="http://feeds.feedburner.com/~r/ODesenvolvedor/~4/VSvkJIgeVKw" height="1" width="1"/>]]></content:encoded>
		<feedburner:origLink>http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/html5-canvas-tutorial-para-iniciantes.html</feedburner:origLink></item>
	
		<item>
		<title>Programador especialista - a inércia em TI</title>
		<link>http://feedproxy.google.com/~r/ODesenvolvedor/~3/1-BX7YzhjY0/programador-especialista-a-inercia-em-ti.html</link>
		<comments>http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/programador-especialista-a-inercia-em-ti.html#comment</comments>
		<pubDate>Tue, 04 Dec 2012 16:00:20 -0300</pubDate>
		<dc:creator>And After - Guilherme Serrano</dc:creator>
	<dc:subject>programacao</dc:subject><dc:subject>carreira</dc:subject>
		<guid isPermaLink="false">http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/programador-especialista-a-inercia-em-ti.html</guid>
		<description><![CDATA[Vale a pena se especializar em uma linguagem, framework ou metodologia ou é mais produtivo conhecer um pouco de tudo?]]></description>
		<content:encoded><![CDATA[<p>
	Resolvi escrever sobre generalismo e especializa&ccedil;&atilde;o em desenvolvimento pois acho que &eacute; um debate interessante e os dois lados tem seus pr&oacute;s e contras. Meu perfil de gostar de aprender e desenvolver coisas diferentes me faz gostar mais do generalismo: me formei em design, sou desenvolvedor front-end no iG e gosto muito de desenvolvimento back-end, que exercito no <a href="http://andafter.org">And After</a>, <a href="http://eucompraria.com.br" title="Eu Compraria! ">Eu Compraria</a> e outros projetos pessoais.</p>
<p>
	Desde que entrei no <a href="http://ig.com.br"><strong>iG</strong></a> estou em contato direto com <strong>NodeJS</strong> (leia <strong><a href="http://andafter.org/blogs/odesenvolvedor/publicacoes/como-instalar-o-nodejs-no-ubuntu-2.html">como instalar o NodeJS no Ubuntu</a></strong>). J&aacute; tinha ouvido falar, tinha achado esquisito o conceito de javascript no back-end mas nunca tinha trabalhado com o Node, apesar da curiosidade.</p>
<p>
	Fiquei curioso e resolvi, antes de sair escrevendo c&oacute;digo e aprender &quot;na marra&quot;, me aprofundar mais em NodeJS, para isso corri para os tutoriais e li alguns &oacute;timos livros:</p>
<ul>
	<li>
		What is Node?</li>
	<li>
		The Node Beginner Book</li>
	<li>
		Hands on NodeJS</li>
	<li>
		Mastering NodeJS</li>
</ul>
<p>
	N&atilde;o terminei de ler todos os livros ainda, e tamb&eacute;m n&atilde;o fiz nenhuma aplica&ccedil;&atilde;o em node, mas os livros me despertaram a curiosidade do debate&nbsp;<strong>desenvolvedor generalista vs desenvolvedor especialista.&nbsp;</strong></p>
<p>
	O Daniel Sperb j&aacute; escreveu sobre <a href="http://andafter.org/publicacoes/formacao-generalista_716.html">forma&ccedil;&atilde;o generalista no design</a>, e resolvi iniciar o debate no desenvolveimtno, o que &eacute; melhor: conhecer de forma um pouco mais rasa diversas linguagens e m&eacute;todos ou se especializar em uma &uacute;nica linguagem ou m&eacute;todo?</p>
<p>
	Brett defende a id&eacute;ia (e me convenceu disso) de que &eacute; melhor conhecer diversas metodologias, linguagens e frameworks do que ser um especialista em uma &uacute;nica linguagem, m&eacute;todo ou framework. Segue uma cita&ccedil;&atilde;o do livro:</p>
<blockquote>
	<p>
		&quot;It&#39;s simply this: use different solutions for different problems. Even better, use the right solution for a particular problem&quot;</p>
	<p>
		&Eacute; simplesmente isso: use diferentes solu&ccedil;&otilde;es para diferentes problemas. Ainda melhor, use a solu&ccedil;&atilde;o certa para um problema espec&iacute;fico.</p>
	<p>
		Brett McLaughin, What is Node?</p>
</blockquote>
<p>
	Eu comecei programando em <strong>PHP</strong>, fui para o <strong>ASP</strong> por causa de um emprego, voltei a programar <strong>PHP</strong> e aprendi o framework <strong>Code Igniter</strong> (que eu adoro) e gra&ccedil;as ao <strong>Well</strong> estou aprendendo <strong>CakePHP</strong> agora, um outro framework <strong>PHP</strong>. Tamb&eacute;m estou estudando NodeJS, mas na verdade no iG sou desenvolvedor front-end: HTML5, CSS e javascript (com jQuery).</p>
<p>
	<img alt="" src="http://andafter.org/media/users/26/album/random/sniper.jpg" style="width: 640px; height: 480px; " /></p>
<p style="text-align: center; ">
	Especialista: t&atilde;o focado em uma solu&ccedil;&atilde;o que pode n&atilde;o<br />
	visualizar nada em sua vis&atilde;o perif&eacute;rica.</p>
<p>
	N&atilde;o defendo a id&eacute;ia de apenas &quot;arranhar&quot; em uma d&uacute;zia de linguagens e n&atilde;o saber nenhuma direito, mas acho muito v&aacute;lido ter a mente aberta a novas tecnologias e id&eacute;ias se aprofundar um pouco e dominar o b&aacute;sico de linguagem, e a&iacute; partir para fazer a mesma coisa em outra (ou em outro framework). Sei qun&atilde;o &eacute; poss&iacute;vel (e nem deve ser saud&aacute;vel) fazer isso com todas ou a maioria das linguagens, mas com algumas.</p>
<p>
	No CodeIgniter hoje eu me sinto a vontade para desenvolver qualquer coisa - mas o Well me apresentou algumas facilidades do <strong>Cake</strong> (bake e outras artimanhas para pregui&ccedil;osos) que n&atilde;o sei se existe no <strong>CI</strong>, e essa &eacute; uma forma de &quot;abrir a cabe&ccedil;a&quot; &nbsp;a novas id&eacute;ias, talvez meu pr&oacute;ximo projeto seja em Cake e n&atilde;o em CI, porque n&atilde;o?</p>
<h2>
	A in&eacute;rcia no mundo de TI</h2>
<p>
	A verdade &eacute; que, no geral, somos pregui&ccedil;osos e reagimos negativamente a mudan&ccedil;as. Quem &eacute; empreendedor n&atilde;o pode agir desta forma, e os profissionais pr&oacute;-ativos tamb&eacute;m n&atilde;o deveriam. As mudan&ccedil;as tamb&eacute;m s&atilde;o oportunidades: estar a frente tecnologicamente, aprender novas tecnologias, se promover, reduzir custos.&nbsp;</p>
<p>
	A mudan&ccedil;a pode trazer muitos benef&iacute;cios, mas para isso voc&ecirc; deve combater a in&eacute;rcia de deixar de fazer as coisas exatamente do mesmo modo que voc&ecirc; fazia antes.</p>
<p>
	<strong><a href="http://andafter.org/blogs/odesenvolvedor/tag/php">PHP</a></strong> resolve tudo? Talvez, com uma gambiarra aqui ou ali. E isso serve para qualquer outra linguagem, sei que um especialista faz o que quiser com a linguagem que domina, talvez com alguma <em>deseleg&acirc;ncia</em> no c&oacute;digo aqui ou ali, mas ser&aacute; funcional.</p>
<blockquote>
	<p>
		&quot;There&#39;s a certain inertia in not just web design, but all of programming. That inertia can be stated axiomatically like this: the more you learn, and become good at a certain approach or technique or language, the likely are you to use that (...) but this inertia often causes you to use a tool because you know ir, rather than beacause it&#39;s the right tool&quot;.</p>
	<p>
		Brett McLaughin em What is Node?</p>
</blockquote>
<p>
	&Eacute;, de certa forma, natural esta in&eacute;rcia citada pelo Brett, mas &eacute; o motivo pelo qual as gambiarras acontecem.</p>
<p>
	&nbsp;</p>
<h2>
	Dificuldades do generalismo</h2>
<p>
	Acho que o desenvolvedor generalista ainda tende a ser um pouco menos valorizado do que o especialista na &quot;avalia&ccedil;&atilde;o padr&atilde;o&quot; de junior, pleno e senior que o mercado faz. N&atilde;o sei o quanto &eacute; valorizado alguem que domine diversas linguagens e metodologias e que n&atilde;o queira partir para a burocracia gerencial e queira continuar com a &quot;m&atilde;o na massa&quot;.</p>
<p>
	Outra dificuldade que vejo para o generalismo &eacute; se manter atualizado com as diversas tecnologias. Estudar e estar familiarizado com uma tecnologia &eacute; relativamente f&aacute;cil: ler alguns livros, escrever algum c&oacute;digo para testar e montar um projeto. Em menos de um ano, se voc&ecirc; tem alguma experi&ecirc;ncia com outras linguagens, voc&ecirc; j&aacute; &quot;se d&aacute; bem&quot; com uma linguagem ou framework, mas e se manter atualizado em duas ou tr&ecirc;s linguagens? Acho que isso requer um pouco mais de estudo do que um programador que s&oacute; le os &uacute;ltimos releases do PHP e do MySQL, por exemplo (com todo respeitos aos especialistas que se revoltar&atilde;o com este texto).</p>
<h2>
	Vantagens do especialista</h2>
<p>
	Neste post explorei as vantagens que vejo no generalismo, quando voc&ecirc; precisar de chegar em um ponto de conhecimento que o generalismo n&atilde;o proporcionou, voc&ecirc; certamente vai penar um pouco mais que o especialista - e se isso se tornar constante em um projeto talvez seja hora de rever se n&atilde;o compensa contratar um especialista, no caso de n&atilde;o existir outra ferramenta (linguagem, framework, etc) que voc&ecirc; domine que sirva para resolver o seu problema.</p>
<p>
	Sei que o especialista tamb&eacute;m tem suas vantagens sobre o generalista. Provavelmente a qualidade de c&oacute;digo ser&aacute; um pouquinho melhor, talvez ele saiba explorar melhor ferramentas e bibliotecas espec&iacute;ficas para cada situa&ccedil;&atilde;o, resultando em uma performance mais avan&ccedil;ada, ou numa economia de servidor.</p>
<p>
	Para situa&ccedil;&otilde;es muito espec&iacute;ficas ou de extrema performance, provavelmente um especialista tamb&eacute;m saiba como explorar melhor de forma exaustiva uma linguagem.</p>
<p>
	&nbsp;</p>
<p>
	&nbsp;</p>
<p>
	Quero a opini&atilde;o dos leitores, voc&ecirc; prefere ser um especialista ou generalista? E para contratar, acha mais vantagem contratar um especialista ou generalista? Porque?</p>
<img src="http://feeds.feedburner.com/~r/ODesenvolvedor/~4/1-BX7YzhjY0" height="1" width="1"/>]]></content:encoded>
		<feedburner:origLink>http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/programador-especialista-a-inercia-em-ti.html</feedburner:origLink></item>
	
		<item>
		<title>PHP - Função com número de parâmetros indefinido</title>
		<link>http://feedproxy.google.com/~r/ODesenvolvedor/~3/gjm8UcA9tY4/php-funcao-com-numero-de-parametros-variavel.html</link>
		<comments>http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/php-funcao-com-numero-de-parametros-variavel.html#comment</comments>
		<pubDate>Thu, 04 Oct 2012 16:27:41 -0300</pubDate>
		<dc:creator>And After - Wellington Santos</dc:creator>
	<dc:subject>php</dc:subject><dc:subject>zce</dc:subject><dc:subject>funcao</dc:subject>
		<guid isPermaLink="false">http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/php-funcao-com-numero-de-parametros-variavel.html</guid>
		<description><![CDATA[Saiba como criar uma função que pode receber infinitos parâmetros e como resgatá-los.]]></description>
		<content:encoded><![CDATA[<p>
	Para criar uma fun&ccedil;&atilde;o que recebe um n&uacute;mero vari&aacute;vel de par&acirc;metros precisaremos conhecer as fun&ccedil;&otilde;es built-in do PHP, func_num_args, func_get_args,&nbsp;e func_get_arg.</p>
<div>
	- func_num_args() - Retorna a quantidade de argumentos passados para a fun&ccedil;&atilde;o</div>
<div>
	- func_get_args() - Retorna array de argumentos passados para a fun&ccedil;&atilde;o</div>
<div>
	- func_get_arg(int $pos)&nbsp;- Retorna o argumento da posi&ccedil;&atilde;o informada</div>
<div>
	&nbsp;</div>
<div>
	Exemplo:</div>
<div>
	&nbsp;</div>
<pre>
<code>function hello() { 
	if (func_num_args() &gt; 0) {
		$args = func_get_args(); 
		foreach($args as $arg){
			echo $arg; 
		} 
	} else { 
		echo &quot;Voc&ecirc; n&atilde;o passou nenhum param&quot;; 
	} 
} 
hello(&quot;andafter&quot;,&quot;.&quot;,&quot;org&quot;); // Aparecer&aacute; &quot;andafter.org&quot;
hello(); // Aparecer&aacute; &quot;Voc&ecirc; n&atilde;o passou nenhum param&quot; </code></pre><img src="http://feeds.feedburner.com/~r/ODesenvolvedor/~4/gjm8UcA9tY4" height="1" width="1"/>]]></content:encoded>
		<feedburner:origLink>http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/php-funcao-com-numero-de-parametros-variavel.html</feedburner:origLink></item>
	
		<item>
		<title>PHP, escovando bits</title>
		<link>http://feedproxy.google.com/~r/ODesenvolvedor/~3/GfIqaasfb8w/php-escovando-bits.html</link>
		<comments>http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/php-escovando-bits.html#comment</comments>
		<pubDate>Thu, 04 Oct 2012 13:31:51 -0300</pubDate>
		<dc:creator>And After - Wellington Santos</dc:creator>
	<dc:subject>php</dc:subject><dc:subject>zce</dc:subject><dc:subject>zce-basico</dc:subject>
		<guid isPermaLink="false">http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/php-escovando-bits.html</guid>
		<description><![CDATA[Quais operações para trabalhar bit a bit no PHP]]></description>
		<content:encoded><![CDATA[<h2>
	- &quot;&amp;&quot; - Porta L&oacute;gica AND</h2>
<h3>
	Tabela da Verdade:&nbsp;</h3>
<table border="1" cellpadding="1" cellspacing="1" style="width: 200px; ">
	<tbody>
		<tr>
			<td>
				A</td>
			<td>
				B</td>
			<td>
				A &amp; B</td>
		</tr>
		<tr>
			<td>
				0</td>
			<td>
				0</td>
			<td>
				0</td>
		</tr>
		<tr>
			<td>
				0</td>
			<td>
				1</td>
			<td>
				0</td>
		</tr>
		<tr>
			<td>
				1</td>
			<td>
				0</td>
			<td>
				0</td>
		</tr>
		<tr>
			<td>
				1</td>
			<td>
				1</td>
			<td>
				1</td>
		</tr>
	</tbody>
</table>
<p>
	&nbsp;</p>
<h3>
	C&oacute;digo:&nbsp;</h3>
<p>
<!--?php</p--></p>
<p>
	$a = 1;</p>
<p>
	$b = 0;</p>
<p>
	if($a &amp; $b){</p>
<p>
	echo &quot;Teste AND: true&quot;;</p>
<p>
	}else{</p>
<p>
	echo &quot;Teste AND: false&quot;;</p>
<p>
	}</p>
<p>
	?&gt;</p>
<p>
	Obs: S&oacute; ser&aacute; true se os valores de A e B forem 1</p>
<p>
	&nbsp;</p>
<h2>
	- &quot;|&quot; - Porta l&oacute;gica OR</h2>
<h3>
	Tabela da Verdade:&nbsp;</h3>
<table border="1" cellpadding="1" cellspacing="1" style="width: 200px; ">
	<tbody>
		<tr>
			<td>
				A</td>
			<td>
				B</td>
			<td>
				A | B</td>
		</tr>
		<tr>
			<td>
				0</td>
			<td>
				0</td>
			<td>
				0</td>
		</tr>
		<tr>
			<td>
				0</td>
			<td>
				1</td>
			<td>
				1</td>
		</tr>
		<tr>
			<td>
				1</td>
			<td>
				0</td>
			<td>
				1</td>
		</tr>
		<tr>
			<td>
				1</td>
			<td>
				1</td>
			<td>
				1</td>
		</tr>
	</tbody>
</table>
<p>
	&nbsp;</p>
<h3>
	C&oacute;digo:&nbsp;</h3>
<p>
<!--?php</p--></p>
<p>
	$a = 1;</p>
<p>
	$b = 0;</p>
<p>
	if($a | $b){</p>
<p>
	echo &quot;Teste OR: true&quot;;</p>
<p>
	}else{</p>
<p>
	echo&nbsp;&quot;Teste OR: false&quot;;</p>
<p>
	}</p>
<p>
	?&gt;</p>
<p>
	Obs: S&oacute; ser&aacute; true se os valores de A ou B ou ambos for(em) 1</p>
<div>
	&nbsp;</div>
<h2>
	- &quot;^&quot; - Porta l&oacute;gica XOR</h2>
<h3>
	Tabela da verdade:</h3>
<div>
	&nbsp;</div>
<div>
	<table border="1" cellpadding="1" cellspacing="1" style="width: 200px; ">
		<tbody>
			<tr>
				<td>
					A</td>
				<td>
					B</td>
				<td>
					A ^ B</td>
			</tr>
			<tr>
				<td>
					0</td>
				<td>
					0</td>
				<td>
					0</td>
			</tr>
			<tr>
				<td>
					0</td>
				<td>
					1</td>
				<td>
					1</td>
			</tr>
			<tr>
				<td>
					1</td>
				<td>
					0</td>
				<td>
					1</td>
			</tr>
			<tr>
				<td>
					1</td>
				<td>
					1</td>
				<td>
					0</td>
			</tr>
		</tbody>
	</table>
	<p>
		&nbsp;</p>
	<h3>
		&nbsp;</h3>
	<h3>
		C&oacute;digo:&nbsp;</h3>
	<p>
<!--?php</p-->	</p>
	<p>
		$a = 1;</p>
	<p>
		$b = 0;</p>
	<p>
		if($a ^ $b){</p>
	<p>
		echo &quot;Teste XOR: true&quot;;</p>
	<p>
		}else{</p>
	<p>
		echo&nbsp;&quot;Teste XOR: false&quot;;</p>
	<p>
		}</p>
	<p>
		?&gt;</p>
	<p>
		Obs: S&oacute; ser&aacute; true se o valor de A for o contr&aacute;rio de B e vice e versa.</p>
	<p>
		&nbsp;</p>
	<h2>
		- &quot;~&quot; - Porta l&oacute;gica NOT</h2>
	<h3>
		Tabela da verdade:</h3>
	<div>
		<table border="1" cellpadding="1" cellspacing="1" style="width: 200px; ">
			<tbody>
				<tr>
					<td>
						A</td>
					<td>
						~A</td>
				</tr>
				<tr>
					<td>
						0</td>
					<td>
						1</td>
				</tr>
				<tr>
					<td>
						1</td>
					<td>
						0</td>
				</tr>
			</tbody>
		</table>
		<p>
			Obs: O negado &eacute; o inverso do valor de A.</p>
		<p>
			&nbsp;</p>
		<h2>
			- &quot;&gt;&gt;&quot; - Move os bits para a direita</h2>
		<p>
<!--?php</p-->		</p>
		<p>
			$num = 8; //Em binario, 1000</p>
		<p>
			$num = $num &gt;&gt; 2;&nbsp;</p>
		<p>
			echo $num; //Aparecer&aacute; 2 que em bin&aacute;rio = 0010</p>
		<p>
			?&gt;</p>
		<p>
			&nbsp;</p>
		<p>
			&nbsp;</p>
		<h2>
			- &quot;&lt;&lt;&quot; - Move os bits para a esquerda</h2>
		<p>
<!--?php </p-->		</p>
		<p>
			$num = 2; //Em binario, 0010</p>
		<p>
			$num = $num &lt;&lt; 2;&nbsp;</p>
		<p>
			echo $num; //Aparecer&aacute; 8 que em bin&aacute;rio = 1000</p>
		<p>
			?&gt;</p>
	</div>
</div>
<img src="http://feeds.feedburner.com/~r/ODesenvolvedor/~4/GfIqaasfb8w" height="1" width="1"/>]]></content:encoded>
		<feedburner:origLink>http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/php-escovando-bits.html</feedburner:origLink></item>
	
		<item>
		<title>Ponteiros, as variáveis de referência</title>
		<link>http://feedproxy.google.com/~r/ODesenvolvedor/~3/00Y2Z60Rp8o/ponteiros-as-variaveis-de-referencia.html</link>
		<comments>http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/ponteiros-as-variaveis-de-referencia.html#comment</comments>
		<pubDate>Sat, 04 Aug 2012 22:22:04 -0300</pubDate>
		<dc:creator>And After - Wellington Santos</dc:creator>
	<dc:subject>php</dc:subject>
		<guid isPermaLink="false">http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/ponteiros-as-variaveis-de-referencia.html</guid>
		<description><![CDATA[Saiba como e por que trabalhar com ponteiros]]></description>
		<content:encoded><![CDATA[<h2>
	Primeiramente precisamos entender o que &eacute; uma vari&aacute;vel, ent&atilde;o o que &eacute;?&nbsp;</h2>
<div>
	Vari&aacute;vel &eacute; um nome amig&aacute;vel que damos para um espa&ccedil;o reservado na mem&oacute;ria que receber&aacute; alguma informa&ccedil;&atilde;o que desejamos. Exemplo:&nbsp;</div>
<div>
	&nbsp;</div>
<div>
<!--?php</div-->	<div>
		$nome = &quot;Andafter.org&quot;;</div>
	<div>
		?&gt;</div>
	<div>
		&nbsp;</div>
	<div>
		Este trecho de c&oacute;digo diz ao compilador do php o seguinte: Mem&oacute;ria, reserve pra mim um espa&ccedil;o em sua mem&oacute;ria e guarde dentro dele a string &quot;Andafter.org&quot;. Quando pedimos isso, o computador executa essas a&ccedil;&otilde;es e retorna um endere&ccedil;o que este espa&ccedil;o ficou alocado, o endere&ccedil;o de mem&oacute;ria.</div>
	<div>
		&nbsp;</div>
	<div>
		Sabendo agora o que &eacute; um endere&ccedil;o de mem&oacute;ria, vejamos o c&oacute;digo abaixo:&nbsp;</div>
	<div>
		&nbsp;</div>
	<div>
<!--?php</div-->		<div>
			$nome = &quot;google.com&quot;;&nbsp;</div>
		<div>
			$linkNome = &amp;$nome;</div>
		<div>
			$linkNome = &quot;andafter.org&quot;;</div>
		<div>
			&nbsp;</div>
		<div>
			echo $nome; //aparecer&aacute; andafter.org</div>
		<div>
			?&gt;</div>
		<div>
			&nbsp;</div>
		<div>
			Na 1a linha de c&oacute;digo temos uma associa&ccedil;&atilde;o normal, conforme vimos anteriormente.</div>
		<div>
			na 2a linha de c&oacute;digo falamos que $linkNome receber&aacute; o endere&ccedil;o de mem&oacute;ria da vari&aacute;vel $nome, ou seja, $linkNome ser&aacute; um ponteiro para a var $nome.</div>
		<div>
			Na 3a linha modificamos a var $linkNome que na verdade &eacute; uma refer&ecirc;ncia a vari&aacute;vel $nome alterando assim o conte&uacute;do da vari&aacute;vel que est&aacute; apontando.</div>
		<h2>
			Onde usar ponteiros?&nbsp;</h2>
		<div>
			Ponteiros s&atilde;o usados juntos com fun&ccedil;&otilde;es, sendo estes em forma de par&acirc;metros ou em retornos.</div>
		<div>
			Exemplo:</div>
		<div>
			&nbsp;</div>
		<div>
<!--?php </div-->			<div>
				$frutas = [&quot;ma&ccedil;a&quot;,&quot;pera&quot;,&quot;abacate&quot;];</div>
			<div>
				&nbsp;</div>
			<div>
				sort($frutas);</div>
			<div>
				&nbsp;</div>
			<div>
				var_dump($frutas);</div>
			<div>
				?&gt;</div>
			<div>
				&nbsp;</div>
			<div>
				A fun&ccedil;&atilde;o sort, que ordena um array, recebe uma refer&ecirc;ncia de vari&aacute;vel e faz a modifica&ccedil;&atilde;o a partir da refer&ecirc;ncia informada.</div>
			<div>
				Veja a assinatura do m&eacute;todo sort:&nbsp;</div>
			<div>
				&nbsp;</div>
			<div>
				bool sort ( array &amp;$array [, int $sort_flags ] )&nbsp;</div>
			<h2>
				Porque usar ponteiros?</h2>
			<div>
				Os ponteiros evitam c&oacute;pias desnecess&aacute;rias para os escopos locais das fun&ccedil;&otilde;es. Toda vez que uma fun&ccedil;&atilde;o recebe um par&acirc;metro, ela mesma cria uma c&oacute;pia da vari&aacute;vel em mem&oacute;ria para trabalhar dentro de si mesma, veja nos exemplos abaixo:</div>
			<div>
				&nbsp;</div>
			<div>
				<strong>Exemplo 1: vari&aacute;veis duplicadas em mem&oacute;ria:&nbsp;</strong></div>
			<div>
				&nbsp;</div>
			<div>
<!--?php</div-->				<div>
					&nbsp;</div>
				<div>
					function dobraValor($valor){</div>
				<div>
					&nbsp; &nbsp; &nbsp; &nbsp; return $valor * 2;</div>
				<div>
					}</div>
				<div>
					&nbsp;</div>
				<div>
					$valor = 2;</div>
				<div>
					&nbsp;</div>
				<div>
					$valor = dobraValor($valor);</div>
				<div>
					?&gt;</div>
				<div>
					&nbsp;</div>
				<div>
					Explica&ccedil;&atilde;o: Neste exemplo teremos 2 vari&aacute;veis $valor; uma de escopo global e uma de escopo local dentro da fun&ccedil;&atilde;o ambas contendo o mesmo conte&uacute;do.</div>
				<div>
					&nbsp;</div>
				<div>
					<strong>Exemplo 2: uma vari&aacute;vel e trabalhando com refer&ecirc;ncia</strong></div>
				<div>
					&nbsp;</div>
				<div>
<!--?php </div-->					<div>
						&nbsp;</div>
					<div>
						function dobraValor(&amp;$valor){</div>
					<div>
						&nbsp; &nbsp; &nbsp; &nbsp; $valor = $valor * 2;</div>
					<div>
						}</div>
					<div>
						&nbsp;</div>
					<div>
						$valor = 2;</div>
					<div>
						&nbsp;</div>
					<div>
						dobraValor($valor);</div>
					<div>
						?&gt;&nbsp;</div>
					<div>
						&nbsp;</div>
					<div>
						Explica&ccedil;&atilde;o: Neste caso, temos apenas 1 vari&aacute;vel $valor, a de escopo global. A fun&ccedil;&atilde;o dobraValor recebe apenas uma refer&ecirc;ncia &agrave; vari&aacute;vel de escopo global n&atilde;o criando portanto uma c&oacute;pia da $valor para acesso local.</div>
					<h2>
						Conclus&atilde;o</h2>
					<div>
						Deixamos mais perform&aacute;ticos nossos sitemas trabalhando com ponteiros mas tamb&eacute;m devemos tomar cuidado ao modificar essas vari&aacute;veis por refer&ecirc;ncia pois qualquer atribui&ccedil;&atilde;o de valor a ela, modificaremos a vari&aacute;vel de fora tamb&eacute;m o que pode gerar muita dor de cabe&ccedil;a na hora identificar o porque a vari&aacute;vel est&aacute; dobrando o valor sem vc. mandar.&nbsp;</div>
				</div>
			</div>
		</div>
	</div>
</div>
<img src="http://feeds.feedburner.com/~r/ODesenvolvedor/~4/00Y2Z60Rp8o" height="1" width="1"/>]]></content:encoded>
		<feedburner:origLink>http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/ponteiros-as-variaveis-de-referencia.html</feedburner:origLink></item>
	
		<item>
		<title>XAMP e MySQL no Mac - XAMPPErrorDomain error</title>
		<link>http://feedproxy.google.com/~r/ODesenvolvedor/~3/brjIg2IORr8/xamp-e-mysql-no-mac-xampperrordomain-error.html</link>
		<comments>http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/xamp-e-mysql-no-mac-xampperrordomain-error.html#comment</comments>
		<pubDate>Wed, 04 Jul 2012 10:45:44 -0300</pubDate>
		<dc:creator>And After - Guilherme Serrano</dc:creator>
	<dc:subject>mac-os</dc:subject><dc:subject>mysql</dc:subject><dc:subject>xampp</dc:subject><dc:subject>php</dc:subject>
		<guid isPermaLink="false">http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/xamp-e-mysql-no-mac-xampperrordomain-error.html</guid>
		<description><![CDATA[Solução de um problema do XAMP no MacOS para inicial o MySQL, que dá o erro "XAMPPErrorDomain error 1".]]></description>
		<content:encoded><![CDATA[<p>
	Como tenho pouca experi&ecirc;ncia com Mac OS, quem configurou meu ambiente de desenvolvimento foi meu colega Well, que optoiu pelo XAMPP para a configura&ccedil;&atilde;o do Apache e MySQL.</p>
<p>
	Hoje percebi que o MySQL n&atilde;o estava iniciando, e retornava o erro &quot;XAMPPErrorDomain error 1&quot;, que pelo que pesquisei &eacute; um erro de permiss&atilde;o apenas.</p>
<p>
	&nbsp;</p>
<h2>
	XAMPPErrorDomain error 1</h2>
<p>
	N&atilde;o sei se esta mensagem de erro d&aacute; para outros casos, mas no meu caso ela representava um problema de permiss&atilde;o de execu&ccedil;&atilde;o nos arquivos do MySQL.</p>
<p>
	A solu&ccedil;&atilde;o foi dar um <strong>chmod -R 777 </strong>na pasta do MySQL do XAMPP:</p>
<p>
	<code>sudo chmod -R 777 /Applications/XAMPP/xamppfiles/var/mysql</code></p>
<p>
	Pronto, agora &eacute; s&oacute; iniciar o MySQL atrav&eacute;s do XAMPP Controle e ele deve funcionar corretamente.</p>
<p>
	&nbsp;</p>
<h2>
	phpMyAdmin</h2>
<p>
	Vi que o MySQL estava com o processo rodando corretamente mas quando tentei acessar o phpMyAdmin recebi o seguinte erro:&nbsp;</p>
<p>
	<code>#1 - Can&#39;t create/write to file &#39;/Applications/XAMPP/xamppfiles/temp/#sql274_1_2.MYI&#39; (Errcode: 13)</code></p>
<p>
	Novamente problema de permiss&atilde;o de escrita na pasta indicada, outro chmod:</p>
<p>
	<code><span style="font-family: monospace; ">sudo chmod -R 777 /Applications/XAMPP/xamppfiles/temp</span></code></p>
<p>
	Problema resolvido, MySQL rodando e phpMyAdmin funcionando corretamente. Resolveu este problema de outra forma? Compartilha nos coment&aacute;rios para eu manter o post atualizado. <strong>:)</strong></p>
<img src="http://feeds.feedburner.com/~r/ODesenvolvedor/~4/brjIg2IORr8" height="1" width="1"/>]]></content:encoded>
		<feedburner:origLink>http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/xamp-e-mysql-no-mac-xampperrordomain-error.html</feedburner:origLink></item>
	
		<item>
		<title>O que é Page Visibility - Palestra do SampaJS</title>
		<link>http://feedproxy.google.com/~r/ODesenvolvedor/~3/Hbl9ysqLEGU/o-que-e-page-visibility-palestra-do-sampajs.html</link>
		<comments>http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/o-que-e-page-visibility-palestra-do-sampajs.html#comment</comments>
		<pubDate>Sat, 04 Feb 2012 13:32:25 -0300</pubDate>
		<dc:creator>And After - Guilherme Serrano</dc:creator>
	<dc:subject>javascript</dc:subject><dc:subject>html</dc:subject><dc:subject>front-end</dc:subject><dc:subject>programacao</dc:subject><dc:subject>web</dc:subject>
		<guid isPermaLink="false">http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/o-que-e-page-visibility-palestra-do-sampajs.html</guid>
		<description><![CDATA[Palestra do Daniel Filho no SampaJS, falando sobre o recurso Page Visibility.]]></description>
		<content:encoded><![CDATA[<p>
	Pelo segundo ano consecutivo o SampaJS aconteceu quando eu estava viajando e n&atilde;o pude participar. O <strong><a href="http://danielfilho.info/blog/">Daniel Filho</a></strong> falou sobre <strong>Page Visibility</strong>, uma API bacana que permite melhorar ainda mais a intera&ccedil;&atilde;o com o usu&aacute;rio verificando se sua p&aacute;gina est&aacute; ativa no navegador do usu&aacute;rio.</p>
<h2>
	Page Visibility</h2>
<p>
	<iframe allowfullscreen="" frameborder="0" height="360" src="http://www.youtube.com/embed/THsq35jbC7I" width="640"></iframe></p>
<p>
	&nbsp;</p>
<p>
	E se voc&ecirc; quer saber mais sobre Page Visibility vale a pena ver a <a href="http://www.w3.org/TR/2011/WD-page-visibility-20110602/">documenta&ccedil;&atilde;o na W3C</a>.</p>
<img src="http://feeds.feedburner.com/~r/ODesenvolvedor/~4/Hbl9ysqLEGU" height="1" width="1"/>]]></content:encoded>
		<feedburner:origLink>http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/o-que-e-page-visibility-palestra-do-sampajs.html</feedburner:origLink></item>
	
		<item>
		<title>Javascript - o método call() e apply()</title>
		<link>http://feedproxy.google.com/~r/ODesenvolvedor/~3/Bl290UR5QSs/javascript-o-metodo-call-e-apply.html</link>
		<comments>http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/javascript-o-metodo-call-e-apply.html#comment</comments>
		<pubDate>Wed, 31 Dec 1969 10:27:46 -0300</pubDate>
		<dc:creator>And After - Guilherme Serrano</dc:creator>
	<dc:subject>javascript</dc:subject><dc:subject>front-end</dc:subject><dc:subject>web</dc:subject><dc:subject>programacao</dc:subject>
		<guid isPermaLink="false">http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/javascript-o-metodo-call-e-apply.html</guid>
		<description><![CDATA[Conheça os métodos call e apply que todas as funções do javascript possuem e como ele pode ser utilizado.]]></description>
		<content:encoded><![CDATA[<p>
	Todas as fun&ccedil;&otilde;es do <strong>javascript</strong> possuem alguns m&eacute;todos como toString(), call() e apply(). Antes de explicar o m&eacute;todo function.call() vou exemplificar o funcionamento das fun&ccedil;&otilde;es e escopos, que acredito que isso facilite o entendimento.</p>
<p>
	Exemplo de c&oacute;digo:</p>
<p>
	<code>var url = &#39;andafter.org&#39;;<br />
	function f(){<br />
	&nbsp; &nbsp; console.log(this);<br />
	&nbsp; &nbsp; console.log(this.url);<br />
	}<br />
	f();</code></p>
<p>
	Nesse c&oacute;digo eu seto uma vari&aacute;vel global url, e quando chamo a fun&ccedil;&atilde;o f dou um log em &quot;this&quot; (&eacute; a window), ent&atilde;o quando chamo this.url o retorno &eacute; a vari&aacute;vel instanciada fora da fun&ccedil;&atilde;o.</p>
<h2>
	O m&eacute;todo call()</h2>
<p>
	O m&eacute;todo function.call() permite voc&ecirc; dizer em qual escopo (essa &eacute; a nomenclatura certa? comentem suas opini&otilde;es)&nbsp;uma fun&ccedil;&atilde;o deve ser executada.</p>
<p>
	Voltando ao exemplo de c&oacute;digo anterior:</p>
<p>
	<code>var&nbsp;url&nbsp;=&nbsp;&#39;andafter.org&#39;;<br />
	var site = { url : &#39;odesenvolvedor.com.br&#39; };<br />
	function&nbsp;f(){<br />
	&nbsp; &nbsp; console.log(this.url);<br />
	}<br />
	f.call(site);</code></p>
<p>
	O function.call() define o que ser&aacute; o &quot;this&quot; dentro da fun&ccedil;&atilde;o, e este deve ser passado como par&acirc;metro para o m&eacute;todo call.</p>
<h2>
	&nbsp;</h2>
<h2>
	M&eacute;todo call com par&acirc;metros</h2>
<p>
	No exemplo anterior n&atilde;o fizemos uso de par&acirc;metros, apenas do &quot;this&quot;. Mas o m&eacute;todo call pode receber a partir do segundo par&acirc;meto (o primeiro sempre ser&aacute; o escopo que ser&aacute; atribu&iacute;do ao this) os par&acirc;metros que ser&atilde;o passados para a fun&ccedil;&atilde;o.</p>
<br />
<p>
	<code>var url = &#39;andafter.org&#39;;<br />
	var site = { url : &#39;odesenvolvedor.com.br&#39; };<br />
	function f(p1, p2){<br />
	&nbsp; &nbsp;&nbsp;console.log(this.url + &#39; - &#39; + p1 + &#39; - &#39; + p2);<br />
	}<br />
	f(&#39;aprendendo javascript&#39;, &#39;no andafter!&#39;);<br />
	f.call(site, &#39;estudando c&oacute;digos&#39;, &#39;no desenvolvedor&#39;);</code></p>
<h2>
	O m&eacute;todo function.apply()</h2>
<p>
	O m&eacute;todo function.apply() tem o mesmo funcionamento do function.call() com uma diferen&ccedil;a na forma dos par&acirc;metros, o segundo par&acirc;metro sempre dever&aacute; ser um array, contendo todos os par&acirc;metros que ser&atilde;o enviados para a fun&ccedil;&atilde;o.</p>
<p>
	O primeiro par&acirc;metro continua sendo o escopo onde sua fun&ccedil;&atilde;o ser&aacute; executada.</p>
<p>
	<code><span class="js-keyword">var </span><span class="js-variable">url </span><span class="js-operator">= </span><span class="js-string">&#39;andafter.org&#39;</span><span class="js-punctuation">;</span><br />
	<span class="js-keyword">var </span><span class="js-variable">site </span><span class="js-operator">= </span><span class="js-punctuation">{ </span><span class="js-property">url </span><span class="js-punctuation">: </span><span class="js-string">&#39;odesenvolvedor.com.br&#39; </span><span class="js-punctuation">}</span><span class="js-punctuation">;</span><br />
	<span class="js-keyword">function </span><span class="js-variable">f</span><span class="js-punctuation">(</span><span class="js-variabledef">p1</span><span class="js-punctuation">, </span><span class="js-variabledef">p2</span><span class="js-punctuation">)</span><span class="js-punctuation">{</span><br />
	<span class="whitespace">&nbsp; &nbsp;&nbsp;</span><span class="js-variable">console</span><span class="js-punctuation">.</span><span class="js-property">log</span><span class="js-punctuation">(</span><span class="js-localvariable">this</span><span class="js-punctuation">.</span><span class="js-property">url </span><span class="js-operator">+ </span><span class="js-string">&#39; - &#39; </span><span class="js-operator">+ </span><span class="js-localvariable">p1 </span><span class="js-operator">+ </span><span class="js-string">&#39; &#39; </span><span class="js-operator">+ </span><span class="js-localvariable">p2</span><span class="js-punctuation">)</span><span class="js-punctuation">;</span><br />
	<span class="js-punctuation">}</span><br />
	<span class="js-variable">f</span><span class="js-punctuation">(</span><span class="js-string">&#39;aprendendo javascript&#39;</span><span class="js-punctuation">, </span><span class="js-string">&#39;no andafter!&#39;</span><span class="js-punctuation">)</span><span class="js-punctuation">;</span><br />
	<span class="js-variable">f</span><span class="js-punctuation">.</span><span class="js-property">apply</span><span class="js-punctuation">(</span><span class="js-variable">site</span><span class="js-punctuation">, </span><span class="js-punctuation">[</span><span class="js-string">&#39;estudando c&oacute;digos&#39;</span><span class="js-punctuation">, </span><span class="js-string">&#39;no desenvolvedor&#39;</span><span class="js-punctuation">]</span><span class="js-punctuation">)</span><span class="js-punctuation">;</span></code></p>
<p>
	Agora voc&ecirc; j&aacute; sabe como definir em qual escopo uma fun&ccedil;&atilde;o ser&aacute; executada, e tamb&eacute;m tem um facilitador para fun&ccedil;&otilde;es que chamam fun&ccedil;&otilde;es.</p>
<p>
	Este &eacute; um post introdut&oacute;rio para alguns c&oacute;digos mais complexos que vir&atilde;o, quase todos resultados das minhas pesquisas de <a href="http://andafter.org/blogs/odesenvolvedor/publicacoes/extreme-javascript-performance_1400.html">performance de javascript</a> e desenvolvimento de bibliotecas como o <a href="http://andafter.org/blogs/odesenvolvedor/publicacoes/lazy-load-com-jquery.html">jQuery Lazy Load</a>.</p>
<img src="http://feeds.feedburner.com/~r/ODesenvolvedor/~4/Bl290UR5QSs" height="1" width="1"/>]]></content:encoded>
		<feedburner:origLink>http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/javascript-o-metodo-call-e-apply.html</feedburner:origLink></item>
	
		<item>
		<title>Automação de código com CakePHP</title>
		<link>http://feedproxy.google.com/~r/ODesenvolvedor/~3/w3m4h_6h0Jc/automacao-de-codigo-com-cakephp.html</link>
		<comments>http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/automacao-de-codigo-com-cakephp.html#comment</comments>
		<pubDate>Wed, 31 Dec 1969 10:38:43 -0300</pubDate>
		<dc:creator>And After - Wellington Santos</dc:creator>
	<dc:subject>cakephp</dc:subject><dc:subject>php</dc:subject><dc:subject>framework</dc:subject>
		<guid isPermaLink="false">http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/automacao-de-codigo-com-cakephp.html</guid>
		<description><![CDATA[Veja como automatizar a geração de código através do framework CakePHP a partir de uma base de dados.]]></description>
		<content:encoded><![CDATA[<p>
	Ap&oacute;s conhecer os <a href="http://andafter.org/publicacoes/cakephp-indroducao-ao-framework.html">conceitos b&aacute;sicos do CakePHP</a>&nbsp;vamos criar a estrutura base para um sistema para cadastro de produtos e categorias de um e-commerce a partir de um modelo de dados do MySQL.&nbsp;</p>
<p>
	Para isso precisaremos de um ambiente com:&nbsp;</p>
<p>
	- <a href="http://www.apachefriends.org/pt_br/xampp-windows.html#2287">XAMPP</a> ou (PHP + MySQL + PHP)</p>
<p>
	- <a href="http://dev.mysql.com/downloads/workbench/#downloads">MySQL Workbench</a></p>
<p>
	- <a href="http://cakephp.org/">CakePHP</a></p>
<h2>
	Banco de Dados</h2>
<p>
	Com o MySQL Workbench, crie uma database chamada ecommerce com 2 tabelas (Products,Categories) e insira informa&ccedil;&otilde;es conforme imagem.</p>
<p>
	Relacionamento: Products hasOne Category || Categories hasMany Products</p>
<p>
	<img alt="" src="http://andafter.org/media/images/album/workbench.png" style="width: 640px; height: 434px; " /></p>
<p>
	&nbsp;</p>
<h2>
	CakePHP</h2>
<p>
	Primeiramente baixar a <a href="http://cakephp.org/">vers&atilde;o stable do CakePHP</a>&nbsp;e extrair na raiz do htdocs do seu apache com o nome de ecommerce.&nbsp;</p>
<p>
	Para quem usa Windows e instalou o XAMPP, dever&aacute; extrair o CakePHP em C:\XAMPP\htdocs\ecommerce.</p>
<p>
	Dentro do diret&oacute;rio ecommerce abra o arquivo: App/Config/database.php.default e altere as informa&ccedil;&otilde;es para conex&atilde;o com o banco de dados e aponte para a database ecommerce previamente criada. Feito isso, salve-o como App/Config/database.php.</p>
<p>
	A config ficar&aacute; assim:&nbsp;</p>
<pre>
<code>public $default = array(
    &#39;datasource&#39; =&gt; &#39;Database/Mysql&#39;,
    &#39;persistent&#39; =&gt; false,
    &#39;host&#39; =&gt; &#39;localhost&#39;,
    &#39;login&#39; =&gt; &#39;user&#39;,
    &#39;password&#39; =&gt; &#39;password&#39;,
    &#39;database&#39; =&gt; &#39;ecommerce&#39;,
    &#39;prefix&#39; =&gt; &#39;&#39;,
    //&#39;encoding&#39; =&gt; &#39;utf8&#39;,
);
</code></pre>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 996px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&nbsp;* For MySQL to connect via socket specify the `unix_socket` parameter instead of `host` and `port`</div>
<div>
	&nbsp;</div>
<h2>
	Automa&ccedil;&atilde;o CakePHP</h2>
<p>
	Ap&oacute;s informar os dados para conex&atilde;o com o banco, acesse http://localhost/ecommerce e verifique se h&aacute; algum problema referente &agrave; conex&atilde;o com banco. Havendo, verifique as informa&ccedil;&otilde;es digitadas no arquivo&nbsp;App/Config/database.php e se o servi&ccedil;o de MySQL est&aacute; rodando.&nbsp;</p>
<p>
	<strong>Para usu&aacute;rios de windows:</strong></p>
<p>
	Antes de continuarmos, precisamos adicionar o PHP ao path do sistema operacional. Para isso, siga o procedimento abaixo:&nbsp;</p>
<p>
	- Bot&atilde;o direito em &#39;Meu Computador&#39;</p>
<p>
	- Clique em Propriedades</p>
<p>
	- Na aba avan&ccedil;ado, clique em vari&aacute;veis de ambiente</p>
<p>
	- Na se&ccedil;&atilde;o &quot;Vari&aacute;veis de ambiente&quot; encontre a linha Path e clique em editar</p>
<p>
	- Adicione ao final da linha o caminho para o arquivo php.exe. Se instalou o XAMPP, apenas adicione ao final da linha o trecho: <strong>;C:\XAMPP\php </strong>(Com o ponto e v&iacute;rgula antes!)</p>
<p>
	- Salve</p>
<p>
	<img alt="" src="http://andafter.org/media/images/album/variavel-ambiente.jpg" style="width: 394px; height: 436px; " /></p>
<p>
	&nbsp;</p>
<h3>
	CakePHP, gere uma aplica&ccedil;&atilde;o a partir da minha database!</h3>
<p>
	- Abra o terminal ou prompt de comando. (Windows + R e digite cmd)</p>
<p>
	- Navegue at&eacute; o diret&oacute;rio do ecommerce. (cd C:\XAMPP\htdocs\ecommerce)</p>
<p>
	- Entre dentro de lib/Cake/Console. (cd lib/Cake/Console)</p>
<p>
	- Execute: php cake.php bake all</p>
<p>
	- Neste ponto ele mostrar&aacute; as tabelas criadas no banco de dados</p>
<p>
	- Digite o n&uacute;mero correspondente a tabela que deseja gerar a aplica&ccedil;&atilde;o</p>
<p>
	<img alt="" src="http://andafter.org/media/images/album/bake.png" style="width: 640px; height: 406px; " /></p>
<p>
	- Confirme as perguntas posteriores</p>
<p>
	- Repita o mesmo processo para todas as tabelas.&nbsp;</p>
<p>
	&nbsp;</p>
<p>
	<strong>All done! </strong></p>
<p>
	http://localhost/ecommerce/categories</p>
<p>
	Ao acessar, conseguiremos adicionar categorias e produtos!&nbsp;</p>
<p>
	&nbsp;</p>
<p>
	<span class="Apple-style-span" style="font-size: 18px; font-weight: bold; ">Dica</span></p>
<p>
	Para conhecer mais a fundo como o CakePHP trabalha, visualize os arquivos gerados em <strong>app/Model, app/Controller e app/View</strong>. O c&oacute;digo gerado &eacute; limpo e sem gambiarras, extraindo o que o CakePHP tem de melhor.&nbsp;</p>
<p>
	Sua estrutura base para come&ccedil;ar a trabalhar no desenvolvimento do ecommerce est&aacute; criada, o resto compete a voc&ecirc;.</p>
<p>
	Utilize a <a href="http://book.cakephp.org/1.3/en/view/907/Developing-with-CakePHP">documenta&ccedil;&atilde;o do CakePHP</a> para utilizar ao m&aacute;ximo das funcionalidades do framework.&nbsp;</p>
<h2>
	&nbsp;</h2>
<h2>
	Links de Refer&ecirc;ncia</h2>
<p>
	M&eacute;todos e Exemplos -&nbsp;<a href="http://book.cakephp.org/1.3/pt/view/907/Desenvolvendo-com-CakePHP">http://book.cakephp.org/1.3/pt/view/907/Desenvolvendo-com-CakePHP</a></p>
<p>
	Valida&ccedil;&atilde;o de campos -&nbsp;<a href="http://book.cakephp.org/1.3/pt/view/1143/Valida%C3%A7%C3%A3o-de-dados">http://book.cakephp.org/1.3/pt/view/1143/Valida%C3%A7%C3%A3o-de-dados</a></p>
<p>
	+ sobre a Bakery (gera&ccedil;&atilde;o de c&oacute;digo) -&nbsp;<a href="http://book.cakephp.org/1.3/pt/view/1522/Geração-de-código-com-o-Bake">http://book.cakephp.org/1.3/pt/view/1522/Gera&ccedil;&atilde;o-de-c&oacute;digo-com-o-Bake</a></p>
<p>
	&nbsp;</p>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 942px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	public $default = array(</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 942px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&#39;datasource&#39; =&gt; &#39;Database/Mysql&#39;,</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 942px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&#39;persistent&#39; =&gt; false,</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 942px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&#39;host&#39; =&gt; &#39;localhost&#39;,</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 942px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&#39;login&#39; =&gt; &#39;user&#39;,</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 942px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&#39;password&#39; =&gt; &#39;password&#39;,</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 942px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&#39;database&#39; =&gt; &#39;database_name&#39;,</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 942px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	&#39;prefix&#39; =&gt; &#39;&#39;,</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 942px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	//&#39;encoding&#39; =&gt; &#39;utf8&#39;,</div>
<div id="cke_pastebin" style="position: absolute; left: -1000px; top: 942px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden; ">
	);</div>
<img src="http://feeds.feedburner.com/~r/ODesenvolvedor/~4/w3m4h_6h0Jc" height="1" width="1"/>]]></content:encoded>
		<feedburner:origLink>http://andafter.orghttp://odesenvolvedor.andafter.org/publicacoes/automacao-de-codigo-com-cakephp.html</feedburner:origLink></item>
	</channel>
</rss>

