HTML5のcanvasで手書きでお絵かき

トップページJavascript CSS講座⇒HTML5のcanvasで手書きでお絵かき

HTML5のcanvasで手書きでお絵かき


HTML5対応ブラウザであれば、canvasが使えるので可能手書きのWEBサイトを作成することができます。
タブレットとPCの両方に対応するにはマウス(onMouseDown,onMouseMove,onMouseUp)とタッチ(onTouchStart,onTouchMove,onTouchEnd)の両方のイベントを処理する必要があります。

			
	<!DOCTYPE html>
	<html lang="ja">
	<head>
	  <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
	  <title>Mam 手書きお絵かきJavascriptサンプル</title>
	  <meta name="viewport" content="width=devide-width,init-scale=1,user-scalable=no,minimum-scale=1,maximum-scale=1">
	<script>
	var can;
	var ct;
	var ox=0,oy=0,x=0,y=0;
	var mf=false;
	  function mam_draw_init(){
	    //初期設定
	    can=document.getElementById("can");
	    can.addEventListener("touchstart",onDown,false);
	    can.addEventListener("touchmove",onMove,false);
	    can.addEventListener("touchend",onUp,false);
	    can.addEventListener("mousedown",onMouseDown,false);
	    can.addEventListener("mousemove",onMouseMove,false);
	    can.addEventListener("mouseup",onMouseUp,false);
	    ct=can.getContext("2d");
	    ct.strokeStyle="#000000";
	    ct.lineWidth=5;
	    ct.lineJoin="round";
	    ct.lineCap="round";
	    clearCan();
	  }
	  function onDown(event){
	    mf=true;
	    ox=event.touches[0].pageX-event.target.getBoundingClientRect().left;
	    oy=event.touches[0].pageY-event.target.getBoundingClientRect().top;
	    event.stopPropagation();
	  }
	  function onMove(event){
	    if(mf){
	      x=event.touches[0].pageX-event.target.getBoundingClientRect().left;
	      y=event.touches[0].pageY-event.target.getBoundingClientRect().top;
	      drawLine();
	      ox=x;
	      oy=y;
	      event.preventDefault();
	      event.stopPropagation();
	    }
	  }
	  function onUp(event){
	    mf=false;
	    event.stopPropagation();
	  }
	  
	  function onMouseDown(event){
	    ox=event.clientX-event.target.getBoundingClientRect().left;
	    oy=event.clientY-event.target.getBoundingClientRect().top ;
	    mf=true;
	  }
	  function onMouseMove(event){
	    if(mf){
	      x=event.clientX-event.target.getBoundingClientRect().left;
	      y=event.clientY-event.target.getBoundingClientRect().top ;
	      drawLine();
	      ox=x;
	      oy=y;
	    }
	  }
	  function onMouseUp(event){
	    mf=false;
	  }
	  function drawLine(){
	    ct.beginPath();
	    ct.moveTo(ox,oy);
	    ct.lineTo(x,y);
	    ct.stroke();
	  }
	  function clearCan(){
	    ct.fillStyle="rgb(255,255,255)";
	    ct.fillRect(0,0,can.getBoundingClientRect().width,can.getBoundingClientRect().height);
	  }
	</script>
	</head>
	<body onload="mam_draw_init();">
	    <h3>手書きお絵かきJavascriptサンプル</h3>
	    <div style="border:solid 1px #000000;width:400px;" id="candiv">
	      <canvas id="can" width="400px" height="300px"></canvas>
	    </div>
	    <input type="button" onClick="clearCan();" value="クリア" style="width:100;height:30;" data-inline="true" />
	</body>
	</html>
			
			

javascriptで手書きのサンプル(別ウィンドウ)
Mam's WebSite