「WEBでHTML5のcanvasを使って手書きでお絵かきができるページを作成したい」
ブラウザで手書きでお絵かきができるページ作成したい。
回答
HTML5対応ブラウザであれば、CANVASが使えるので可能ですが、対応していないブラウザでは無理です。
画像形式はPNG形式をお勧めします。iOS、Android、Windowsに安定して使えるからです。
データをサーバーへ送るには、base64エンコードした文字列をhiddenに入れてPOSTするのがいいと思います。
サーバーにデータが届いてからPHPの場合はエクステンションGDを用いてjpg形式に変換するなりすればいいかと思います。
タブレットとPCの両方に対応するにはまた、マウスとタッチの両方のイベントを処理する必要があります。
また、iOSのsafariやタブレット版マイクロソフト社Internet Explorer等はスクロールできない状態でパンをしてスクロールしようとすると、画面が揺れるのでその対応が必要かもしれないです。
https://mam-mam.net/javascript/draw_js.html
以下ソースを参考。
ソース
<!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>