또 다른 시원하고 쉬운 proggie-임의의 상자를 사용하여 이미지에서 페이드!
https://slicker.me/javascript/random_boxes.htm
작동 방식은 다음과 같습니다 (아래 소스 코드).
[Lines 1-4] HTML5 Canvas 설정
[5-6] 소스 이미지
[7-8] Canvas의 2D 컨텍스트를 얻습니다.
[9] 상자의 치수
[10] 난수 상자의 행과 열 수
[12] 이미지가 로드되면 :
[13-14] 상자의 너비와 높이를 계산
[15] 애니메이션을 시작하십시오!
[18-23] 주요 애니메이션 함수 :
[19-20] 임의의 상자를 선택하십시오
[21] 이것이 이 솔루션의 핵심입니다.
이미지의 좌표 (x * boxWidth, y * boxHeight)에서 크기가 boxWidth x boxHeight 인 비트 맵 상자를 이미지에서 Canvas로 복사합니다.
drawImage 함수에 대한 자세한 내용을 보려면 여기를 클릭하십시오.
<html> |
<body> |
<canvas id="myCanvas" width="600" height="373"></canvas> |
<script> |
let image = new Image(); |
image.src = "example1.jpg"; |
let canvas = document.getElementById("myCanvas"); |
let context = canvas.getContext("2d"); |
let boxWidth, boxHeight; |
let rows = 10, columns = 20; |
image.onload = function() { |
boxWidth = image.width / columns; |
boxHeight = image.height / rows; |
requestAnimationFrame(animate); |
}; |
function animate() { |
let x = Math.floor(Math.random() * columns); |
let y = Math.floor(Math.random() * rows); |
context.drawImage(image, x * boxWidth, y * boxHeight, boxWidth, boxHeight, x * boxWidth, y * boxHeight, boxWidth, boxHeight); |
requestAnimationFrame(animate); |
} |
</script> |
</body> |
</html> |
이렇게 하면 영원히 계속 실행되고 코드는 이미 복사 된 상자를 계속 복사합니다.
다음은 두 이미지 사이를 전환하는 더 흥미로운 버전입니다.
이를 위해서는 각 애니메이션 프레임 [26] 후에 증가 할 카운터 [13]를 도입해야 합니다.
[27-28] 카운터가 500에 도달하면 전체 이미지를 표시하십시오. 이것은 두 개 또는 세 개의 상자가 그려지는 상황을 피하기 위해 필요하지만 컴퓨터는 다른 상자를 임의로 선택합니다.
[30-35] 100 프레임 이상이 지나면 소스 이미지를 전환하고 카운터를 재설정 합니다.
<html> |
<body> |
<canvas id="myCanvas" width="600" height="373"></canvas> |
<script> |
let image = new Image(); |
image.src = "example0.jpg"; |
let image2 = new Image(); |
image2.src = "example1.jpg"; |
let canvas = document.getElementById("myCanvas"); |
let context = canvas.getContext("2d"); |
let boxWidth, boxHeight; |
let rows = 10, columns = 20, counter = 0; |
let source = image; |
image2.onload = function() { |
boxWidth = image.width / columns; |
boxHeight = image.height / rows; |
requestAnimationFrame(animate); |
}; |
function animate() { |
let x = Math.floor(Math.random() * columns); |
let y = Math.floor(Math.random() * rows); |
context.drawImage(source, x * boxWidth, y * boxHeight, boxWidth, boxHeight, x * boxWidth, y * boxHeight, boxWidth, boxHeight); |
counter++; |
if (counter == 500) |
context.drawImage(source, 0, 0); |
requestAnimationFrame(animate); |
if (counter == 600) { |
if (source == image) |
source = image2; |
else |
source = image; |
counter = 0; |
} |
} |
</script> |
</body> |
</html> |
등록된 댓글이 없습니다.