맛집 여행 캠핑 일상 생활

CANVAS 이미지 그리기 예제 본문

JAVASCRIPT

CANVAS 이미지 그리기 예제

영은파더♥ 2016. 5. 23. 18:43
728x90

CANVAS 이미지 그리기 예제



PC(마우스) 및 모바일(touch) 브라우저에서도 그리기가 가능한 jQuery 및 HTML 소스입니다.


mousedown -> mousemove -> mouseup (좌표 : e.offsetX, e.offsetY)

touchstart -> touchmove -> touchend (좌표 : e.touches[0].pageX, e.touches[0].pageY)


event 가 서로 다릅니다.


터치스크린은 screenX, screenY, clientX, clientY 가 아닌 pageX Y 값에 canvas 좌표 만큼 빼줘야 합니다.



아래에서 그리기 테스트를 해보세요.


실사용이 가능한 수준으로 만들어 보았습니다.


Canvas not supported



아래는 예제 소스입니다.


<!doctype html>

<html>

<head>

<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no"/>

<script src="//code.jquery.com/jquery.min.js"></script>


<script>

$(document).ready(function(){

var drawCanvas = document.getElementById('drawCanvas');

var drawBackup = new Array();

if (typeof drawCanvas.getContext == 'function') {

var ctx = drawCanvas.getContext('2d');

var isDraw = false;

var width = $('#width').val();;

var color = $('#color').val();

var pDraw = $('#drawCanvas').offset();

var currP = null;


$('#width').bind('change', function(){ width = $('#width').val(); });

$('#color').bind('change', function(){ color = $('#color').val(); });


// 저장된 이미지 호출

if (localStorage['imgCanvas']) {

loadImage();

} else {

ctx.clearRect(0, 0, drawCanvas.width, drawCanvas.height);

}


// Event (마우스)

$('#drawCanvas').bind('mousedown', function(e) {

if (e.button===0) {

saveCanvas();

e.preventDefault();

ctx.beginPath();

isDraw = true;

}

});

$('#drawCanvas').bind('mousemove', function(e) {

var event = e.originalEvent;

e.preventDefault();

currP = { X:event.offsetX, Y:event.offsetY };

if(isDraw) draw_line(currP);

});

$('#drawCanvas').bind('mouseup', function(e) {

e.preventDefault();

isDraw = false;

});

$('#drawCanvas').bind('mouseleave', function(e) {

isDraw = false;

});


// Event (터치스크린)

$('#drawCanvas').bind('touchstart', function(e) {

saveCanvas();

e.preventDefault();

ctx.beginPath();

});

$('#drawCanvas').bind('touchmove', function(e) {

var event = e.originalEvent;

e.preventDefault();

currP = { X:event.touches[0].pageX-pDraw.left, Y:event.touches[0].pageY-pDraw.top };

draw_line(currP);

});

$('#drawCanvas').bind('touchend', function(e) {

e.preventDefault();

});


// 선 그리기

function draw_line(p) {

ctx.lineWidth = width;

ctx.lineCap = 'round';

ctx.lineTo(p.X, p.Y);

ctx.moveTo(p.X, p.Y);

ctx.strokeStyle = color;

ctx.stroke();

}


function loadImage() { // reload from localStorage

var img = new Image();

img.onload = function() {

ctx.drawImage(img, 0, 0);

}

img.src = localStorage.getItem('imgCanvas');

}


function saveImage() { // save to localStorage

var canvas = document.getElementById('drawCanvas');

localStorage.setItem('imgCanvas', canvas.toDataURL('image/png'));

var img =  document.getElementById('saveImg');

img.src = canvas.toDataURL('image/png');

var tmp = $('<a>').attr('download', 'test.png').attr('href', img.src);

tmp[0].click();

tmp.remove();

}


function clearCanvas() {

ctx.clearRect(0, 0, drawCanvas.width, drawCanvas.height);

ctx.beginPath();

localStorage.removeItem('imgCanvas');

}


function saveCanvas() {

drawBackup.push(ctx.getImageData(0, 0, drawCanvas.width, drawCanvas.height));

}


function prevCanvas() {

ctx.putImageData(drawBackup.pop(), 0, 0);

}


$('#btnPrev').click(function() {

prevCanvas();

});


$('#btnClea').click(function() {

clearCanvas();

});


$('#btnSave').click(function() {

saveImage();

});

}

});

</script>

</head>

<body>

<div>

<div align="center">

<canvas id="drawCanvas" width="320" height="320" style="border:1px solid #000000;">Canvas not supported</canvas>

</div>

<div align="center">

<select id="width">

<option value="1">1px</option>

<option value="2">2px</option>

<option value="3" selected>3px</option>

<option value="5">5px</option>

<option value="10">10px</option>

<option value="20">20px</option>

</select>

<select id="color">

<option value="#000000">검정</option>

<option value="#FF0000">빨강</option>

<option value="#00FF00">녹색</option>

<option value="#0000FF">파랑</option>

<option value="#FFFF00">노랑</option>

<option value="#FFFFFF">흰색</option>

</select>

<button id="btnPrev">되돌리기</button>

<button id="btnClea">Clear</button>

<button id="btnSave">다운로드</button>

</div>

</div>

<img id="saveImg" src="" style="display:none;" />

<div style="width:100%;height:800px;">&nbsp;</div>

</body>

</html>


캔버스 이미지 서버에 저장하는 방법 http://itrooms.tistory.com/228



728x90
반응형
Trackback : | Comments :