html에 input을 만들고 type을 file로 설정합니다.
동영상이나 다른 파일이 들어오지 못하게 accept 속성을 이용합니다.
<input id="file" type="file" accept="img/*" />
JS에 변수 선언을 하고 change 이벤트를 만들어 줍니다.
1
2
3
|
const fileInput = document.querySelector("#file");
fileInput.addEventListener("change", fileChange);
|
cs |
change이벤트 함수에 console.dir(event.target);을 해보면
사용자가 선택한 이미지 파일이 브라우저에 들어가 있는 것을 확인할 수 있습니다.
FileList에서 첫번째 파일을 변수로 선언합니다.
(여러 개를 넣을 수 있는 multiple 속성을 input에 추가하면 여러 개를 업로드할 수도 있습니다.
그리고 const url = URL.createObjectURL(file) 이라는 코드를 써줍니다.
이 코드는 특정 파일 객체를 가리키는 새로운 객체 URL을 생성합니다.
참조 : https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
URL.createObjectURL() - Web APIs | MDN
The URL.createObjectURL() static method creates a string containing a URL representing the object given in the parameter.
developer.mozilla.org
url을 console.log()해보면 blob로 시작하는 url이 나옵니다
이 링크를 복사해서 canvas가 열려있는 인터넷 창에 붙여 넣기 하면 사용자가 불러온 이미지를 볼 수 있습니다.
url을 image.src에 넣어줍니다. (html에서 이미지를 불러오는 <img src=""/>랑 똑같음)
1
2
|
const image = new Image();
image.src = url;
|
cs |
마지막으로 이미지가 로드될때 canvas에 이미지를 그려주는 함수를 만듭니다.
addEventListener대신 변수.이벤트 = function(){ }으로도 쓸 수 있습니다.
1
2
3
4
5
6
7
8
9
10
11
|
function fileChange(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, CANVAS_WIDTH, CANVAS_HEIGHT);
fileInput.value = null; //새로운 사진을 불러올수있게 비워줌
};
}
|
cs |
이미지 불러오기 완성!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>study</title>
</head>
<body>
<canvas></canvas>
<div>
<input class="line-width" type="range" min="1" max="10" value="5" step="0.01" />
<input id="color" type="color" />
<div>
<div class="color-option" style="background-color:#ffffff" data-color="#ffffff"></div>
<div class="color-option" style="background-color:#000000" data-color="#000000"></div>
<div class="color-option" style="background-color:#e74c3c" data-color="#e74c3c"></div>
<div class="color-option" style="background-color:#e67e22" data-color="#e67e22"></div>
</div>
</div>
<div class="mode-button">
<button class="painting-btn">그리기모드</button>
<button class="painting-fill-btn">그림채우기</button>
<button class="bg-fill-btn">배경채우기</button>
</div>
<div class="mode-button2">
<button class="save">저장</button>
<button class="new-btn">화면지우기</button>
<button class="eraser-btn">지우개</button>
</div>
<input id="file" type="file" accept="img/*" />
<script src="study.js"></script>
</body>
</html>
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
|
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const lineWidth = document.querySelector(".line-width");
const color = document.querySelector("#color");
const colorOption = Array.from(
document.getElementsByClassName("color-option")
);
const paintingBtn = document.querySelector(".painting-btn");
const paintingFillBtn = document.querySelector(".painting-fill-btn");
const bgFillBtn = document.querySelector(".bg-fill-btn");
const saveBtn = document.querySelector(".save");
const newBtn = document.querySelector(".new-btn");
const eraserBtn = document.querySelector(".eraser-btn");
const fileInput = document.querySelector("#file");
const CANVAS_WIDTH = 400;
const CANVAS_HEIGHT = 400;
//canvas의 넓이 높이가 midContent만큼 꽉차게
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;
ctx.lineWidth = lineWidth.value;
let painting = false;
let filling = false;
function paintingStart() {
painting = true;
}
function paintingEnd() {
if (filling) {
painting = false;
ctx.fill();
ctx.beginPath();
} else {
painting = false;
ctx.beginPath();
}
}
function mouseMove(event) {
if (painting) {
ctx.lineTo(event.offsetX, event.offsetY);
ctx.stroke();
return;
}
ctx.moveTo(event.offsetX, event.offsetY);
}
function lineWidthChange(event) {
ctx.lineWidth = event.target.value;
}
function colorChange(event) {
const colorValue = event.target.value;
ctx.strokeStyle = colorValue;
ctx.fillStyle = colorValue;
ctx.lineWidth = lineWidth.value;
}
function colorClick(event) {
const colorValue = event.target.dataset.color;
ctx.fillStyle = colorValue;
ctx.strokeStyle = colorValue;
color.value = colorValue;
ctx.lineWidth = lineWidth.value;
//사용자가 어떤 색상을 클릭했는지 알 수 있게
//color-input에도 값을 넣어줍니다.
}
function paintingBtnClick() {
filling = false;
ctx.strokeStyle = color.value;
ctx.lineWidth = lineWidth.value;
}
function paintingFillBtnClick() {
filling = true;
ctx.strokeStyle = color.value;
ctx.fillStyle = color.value;
ctx.lineWidth = lineWidth.value;
}
function bgFillBtnClick() {
ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
}
function newBtnClick() {
ctx.fillStyle = "white";
ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
}
function eraserBtnClick() {
ctx.strokeStyle = "white";
ctx.lineWidth = 50;
filling = false;
}
function saveClick() {
const url = canvas.toDataURL();
const a = document.createElement("a");
a.href = url;
a.download = "네임.jpg";
a.click();
}
function fileChange(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, CANVAS_WIDTH, CANVAS_HEIGHT);
fileInput.value = null; //새로운 사진을 불러올수있게 비워줌
};
}
canvas.addEventListener("mousedown", paintingStart);
canvas.addEventListener("mouseup", paintingEnd);
canvas.addEventListener("mousemove", mouseMove);
canvas.addEventListener("mouseleave", paintingEnd);
lineWidth.addEventListener("change", lineWidthChange);
color.addEventListener("change", colorChange);
colorOption.forEach((color) =>
color.addEventListener("click", colorClick)
);
paintingBtn.addEventListener("click", paintingBtnClick);
paintingFillBtn.addEventListener("click", paintingFillBtnClick);
bgFillBtn.addEventListener("click", bgFillBtnClick);
newBtn.addEventListener("click", newBtnClick);
eraserBtn.addEventListener("click", eraserBtnClick);
saveBtn.addEventListener("click", saveClick);
fileInput.addEventListener("change", fileChange);
|
cs |
'코딩이야기 > JS-그림판 만들기' 카테고리의 다른 글
[JavaScript] - 그림판 만들기 완성! (0) | 2022.07.25 |
---|---|
[JavaScript] - 그림판 만들기 ④ (모드바꾸기⑵) (0) | 2022.07.25 |
[JavaScript] - 그림판 만들기 ③ (모드바꾸기⑴) (0) | 2022.07.25 |
[JavaScript] - 그림판 만들기 ② (색깔 선택, 색상표) (0) | 2022.07.25 |
[JavaScript] - 그림판 만들기 ① (그리기, 굵기 조절) (0) | 2022.07.23 |