【HTML5・javascript】canvasにクリックすると動く四角を描く
【今回の内容】
掲題の通り、canvasにクリックすると動く四角を描きました
【処理の流れ】
■キャンパス要素の生成の流れ
①マウス押下時の座標を取得
②マウスを離したときの座標を取得
③キャンパス要素の生成
④キャンパスの色・クリックイベント・キャンパスの大きさを②と③から位置を設定する
⑤要素を挿入する
■クリックイベントの流れ
①pxの数値を切り取る
②移動数値を加算
③繰り返し野設定
※参考にしたサイト
【参考ソース】
<html> <head> <meta charset='utf-8'> </head> <title>HTML5</title> <body id='body'> <div id='div' style="width=800;height=800;"></div> <script> startX=0; startY=0; window.onload=function(){ id=0; stop=""; } body.onmousedown = function(e){ startX=e.pageX; startY=e.pageY; } body.onmouseup =function(e){ var endX=e.pageX; var endY=e.pageY; draw(endX,endY); } function draw(x,y){ var canvas=document.createElement("canvas"); canvas.id=id; canvas.style.backgroundColor = "#00FFFF"; // キャンバスの背景色 canvas.width=Math.abs(x-startX); canvas.height=Math.abs(y-startY); canvas.style.position="absolute"; canvas.onclick=function(){ update_squere(this); }; var context=canvas.getContext('2d'); //描画する四角の座標(mouseup後の座標)がマイナスの時野判定を行う if(x-startX>0 && y-startY>0) { canvas.style.top=startY; canvas.style.left=startX; } else{ canvas.style.top=y; canvas.style.left=x; } body.appendChild(canvas); var array=new Array(); var squ=new square("square",id,canvas.style.top,canvas.style.left,canvas.width,canvas.height); array.push(squ); id=id+1; } function update_squere(elm){ var work=elm.style.top; var updateTop=work.split("px"); updateTop[0]=parseInt(updateTop[0])+5; elm.style.top=updateTop[0]+"px"; stop=setTimeout(function(){ update_squere(elm) },10); if(updateTop[0]>1000){clearTimeout(stop);} } function $(id){ return document.getElementById(id); } </script> </body> </html>