2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

お絵かきできるSNSを作りたい!3

Last updated at Posted at 2020-02-08

お久しぶりです。

前回canvasを使って線を引くことが出来ました。
今回はマウスかペンを使って線を引けるところまで作ります。

基本的にcanvasの上でマウスまたは指を押した座標と動かしている時の座標と離すまでの座標を1ストロークごと書きこめば完成です。

指の場合はtouchstart→touchmove→touchend、
PCの場合はmousedown→mousemove→onMouseUp
のイベントを追加し、それぞれの関数で処理を書きます。

var can;
can=document.getElementById("canvas");
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);

それぞれの関数は以下の通りにしました。

function onDown(event){
	mf=true;
	ox=event.touches[0].pageX-event.target.getBoundingClientRect().left-scx();
	oy=event.touches[0].pageY-event.target.getBoundingClientRect().top -scy();
	event.stopPropagation();
}

function onMouseDown(event){
	mf=true;
	ox=event.clientX-event.target.getBoundingClientRect().left;
	oy=event.clientY-event.target.getBoundingClientRect().top ;
}

function onMove(event){
	if(mf){
		x=event.touches[0].pageX-event.target.getBoundingClientRect().left-scx();
		y=event.touches[0].pageY-event.target.getBoundingClientRect().top -scy();
		drawLine();
		ox=x;
		oy=y;
		event.preventDefault();
		event.stopPropagation();
	}
}

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 onUp(event){
	mf=false;
	event.stopPropagation();
}

function onMouseUp(event){
	mf=false;
}

function drawLine(){
	var ct;
	ct=can.getContext("2d");
	ct.strokeStyle="#000000";
	ct.lineWidth=1;
	ct.lineJoin="round";
	ct.lineCap="round";
	ct.beginPath();
	ct.moveTo(ox,oy);
	ct.lineTo(x,y);
	ct.stroke();
}

function scx(){return document.documentElement.scrollLeft || document.body.scrollLeft;}
function scy(){return document.documentElement.scrollTop  || document.body.scrollTop ;}

これできっと動くはず!

次:お絵かきできるSNSを作りたい!4
最初:お絵かきできるSNSを作りたい!

2
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?