HTML5 Canvas 기초 (3)

캔버스라이브강좌

  • 캔버스 영역에 비디오 입히기
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
<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>

<body>
<h1>Video</h1>
<video class="video" src="./horse.mp4" autoplay muted loop></video>
<canvas class="canvas" width="500" height="300"></canvas>

<script>
const canvas = document.querySelector(".canvas");
const ctx = canvas.getContext("2d");
ctx.font = "bold 50px serif";
ctx.fillStyle = "white";

const subtitle = [
{ time: 1, message: "Melody Lane", x: 270, y: 70 },
{ time: 3, message: "Son of Orfevre", x: 270, y: 170 },
{ time: 5, message: "8th May", x: 270, y: 920 },
];

let canPlayState = false;

ctx.textAlign = "center";
ctx.fillText("loading video...", 250, 150);

const videoElem = document.querySelector(".video");
videoElem.addEventListener("canplaythrough", render); // 이미지는 load, 비디오는 canplaythrough 이벤트를 사용

function render() {
ctx.drawImage(videoElem, 0, 0, 540, 960);

for (let i = 0; i < subtitle.length; i++) {
if (videoElem.currentTime > subtitle[i].time) {
// currentTime 변수는 재생 시간을 나타내고 이는 재생시간에 맞춰 자동으로 증가함
ctx.fillText(subtitle[i].message, subtitle[i].x, subtitle[i].y);
}
}

requestAnimationFrame(render); // 영상이 재렌더링 될 때마다 자막을 시간에 맞춰 전부 입힘
}
</script>
</body>
</html>
  • 비디오의 픽셀 조작
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
const canvas = document.querySelector(".canvas");
const ctx = canvas.getContext("2d");

const videoElem = document.querySelector(".video");
videoElem.addEventListener("canplaythrough", render);

const btnsElem = document.querySelector(".btns");

let imageData;
const particles = [];
let particle;
let colorValue;
let leng;

function render() {
ctx.drawImage(videoElem, 0, 0, 600, 400);
imageData = ctx.getImageData(0, 0, 600, 400);
leng = imageData.data.length / 4;

for (let i = 0; i < leng; i++) {
switch (colorValue) {
case "red":
imageData.data[i * 4 + 0] = 255;
break;
case "green":
imageData.data[i * 4 + 1] = 255;
break;
case "blue":
imageData.data[i * 4 + 2] = 255;
break;
}
}

ctx.putImageData(imageData, 0, 0);
requestAnimationFrame(render);
}

btnsElem.addEventListener("click", function (e) {
colorValue = e.target.getAttribute("data-color");
});