본문 바로가기

프론트엔드/javascript

javascript (16) - 캔버스 만들기 #4 (색채우기, 이미지업로드)

색 채우기, 지우개

Fill - 클릭 시 Fill - Draw 상태 변경 - Fill 상태일 때, 캔버스 크기만큼 사각형 만들기 (채우기효과)

리셋 - 컨버스를 흰색으로 덮는것와 동일

지우개 - 컨버스를 흰색으로 칠하는 것과 동일

 

 

이미지업로드

자바스크립트는 자동으로 내 컴퓨터 파일에 접근할 수 없다. 유저가 파일을 선택해야지만 접근이 가능하다.
인풋에서 이미지 파일을 선택하면 브라우저 자체적으로 해당 이미지를 저장해서  불러올 수 있다.
불러올때 URL주소가 필요함으로 파일정보를 활용하여 생성해야한다.

 

인풋-type="file" 선택될때 모든파일이 선택된다(조건 : accept="img/*" 확장자 상관없이 모든 이미지파일 가능)

인풋 - multiple 속성을 추가하면 여러개의 파일을 업로드할 수 있다. 

file = 선택한 파일정보 (taget.files[0],)  file[0] -> 첫번째 파일이라는 뜻

url = URL.createObjURL(file)

 

위와 같이 생성된 url을 가지고 <img src=""> 이와 같은 태그를 자바스크립트 방식으로 생성해줘야한다.

 

const img = new Image();

img.src=url;

 

이벤트리스너의 또 다른 표기법 

btn.addEventListener("click",move);
btn.click = function() { }; //여기서 함수는 move와 동일한 함수

 

저장된 URL에 이벤트를 할당하여 불러온다.

 

img.onLoad = function() {

 ctx.drawImgae(img,x,y,w,h)

}

 

이미지가 선택된다음에

input (타입:파일) value 초기화 

 


더보기
const fileInput = document.getElementById("file");
const eraser = document.getElementById("eraser");
const mode_reset = document.getElementById("mode_reset");
const mode_fill = document.getElementById("mode_fill");
const line_Widh = document.getElementById("line_Widh");
const line_Color = document.getElementById("line_Color");
const color_options = Array.from(document.getElementsByClassName("color-option"));
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

canvas.width = 800;
canvas.height = 800
ctx.lineWidth = line_Widh.value;
let isPainting = false;
let isFilling = false;

function onMove(event) {

    if (isPainting) {
        ctx.lineTo(event.offsetX, event.offsetY);
        ctx.stroke();
        return;
    }
    ctx.beginPath();
    ctx.moveTo(event.offsetX, event.offsetY);
}

function startPainting() {
    isPainting = true;
}
function canclePainting() {
    isPainting = false;
}
function changeLineWidth(event) {
    ctx.lineWidth = event.target.value;
}

function onRest(event) {
    ctx.fillStyle= "white";
    ctx.fillRect(0,0,800,800);
}

// function changeLineColor(event) {
//     ctx.strokeStyle=event.target.value;
//     ctx.fillStyle=event.target.value;
// }
// function onColorClick(event) {
//     // console.dir(event.target);
//     // console.dir(event.target.dataset.color);
//     const colorValue = event.target.dataset.color;
//     ctx.strokeStyle=colorValue;
//     ctx.fillStyle=colorValue;
//     line_Color.value=colorValue;
// }

function changeColor(event) {
    const dataSetColor = event.target.dataset.color;
    const colorValue = event.target.value
    if (dataSetColor === undefined) {
        ctx.strokeStyle = colorValue;
        ctx.fillStyle = colorValue;
    } else {
        ctx.strokeStyle = dataSetColor;
        ctx.fillStyle = dataSetColor;
        line_Color.value = dataSetColor;
    }
}

function onMode() {
    if (isFilling) {
        isFilling = false;
        mode_fill.innerText = `Fill`
    } else {
        isFilling = true;
        mode_fill.innerText = `Draw`
    }   
}
function onFillColor(){
    if(isFilling) {
        ctx.fillRect(0,0,800,800);
    }
}
function onEraser() {
    ctx.strokeStyle="white";
    isFilling = false;
    mode_fill.innerText = `Fill`
}

function onFile(event) {
    const file = event.target.files[0];
    const url = URL.createObjectURL(file);
    const image = new Image();
    image.src=url;
    image.onload = function() {
     ctx.drawImage(image,0,0,800,800);
     fileInput.value=null;   
    }}

canvas.addEventListener("mousemove", onMove);
canvas.addEventListener("mousedown", startPainting);
canvas.addEventListener("mouseup", canclePainting);
canvas.addEventListener("mouseleave", canclePainting);
line_Widh.addEventListener("change", changeLineWidth);

line_Color.addEventListener("change", changeColor);
color_options.forEach(color => color.addEventListener("click", changeColor));
mode_fill.addEventListener("click", onMode);
canvas.addEventListener("click",onFillColor);
mode_reset.addEventListener("click",onRest);
eraser.addEventListener("click",onEraser);
fileInput.addEventListener("change",onFile)

 

반응형