内容简介
前几天看到一篇文章,利用echarts来实现气泡龙的效果,觉得可以从这个例子衍生出使用不同背景图来实现不同排版的效果;本文介绍利用该思路实现心形图片的排列效果。
实现过程
实现思路分析:
1、绘制本地图片到画布(ctx.drawImage);
2、获取图片的像素点(imageData);
3、根据图片的宽高和设置的间隔进行循环,当为黑色时(r + g + b == 0),就替换为设置的小图片,并把图片加到页面上。
Tips:因为第三点,所以图片要使用纯黑,不然效果会有差异;如果没有纯黑图片,也可以先使用echarts把本地图片转化为纯黑。
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,Chrome=1" />
<title>canvas</title>
<link rel="shortcut icon" href="#" />
<style>
body {
background-color: #333;
}
.photo {
position: absolute;
}
</style>
</head>
<body>
<div id='container'></div>
<canvas id='canvas' style="display: none;"></canvas>
<script>
window.onload = function() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var image = new Image();
image.src = "./images/heart.jpg";
image.onload = function() {
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0);
fillPhoto(ctx, image);
}
}
// 心形填充为小图片
function fillPhoto(ctx, image) {
var imageData = ctx.getImageData(0, 0, image.width, image.height).data;
ctx.clearRect(0, 0, image.width, image.height);
var n = 1;
var gap = 50; // 间隔
var heartContainer = document.getElementById("container");
var heartScale = 2; // 放大倍数
for (var h = 0; h < image.height; h += gap) {
for (var w = 0; w < image.width; w += gap) {
var position = (image.width * h + w) * 4;
var r = imageData[position],
g = imageData[position + 1],
b = imageData[position + 2];
if (r + g + b == 0) { // 判断是否黑色
var photo = document.createElement("img");
photo.src = `./images/cba/${n}.jpg`;
photo.setAttribute("class", "photo");
var photoSize = Math.random() * 10 + 80;
photo.style.left = (w * heartScale - photoSize / 2) + "px";
photo.style.top = (h * heartScale - photoSize / 2) + "px";
photo.style.width = photo.style.height = photoSize + "px";
photo.style.animationDuration = Math.random() * 6 + 4 + "s";
heartContainer.appendChild(photo);
// 由于图片不够多,使用循环
n++;
n = n > 6 ? 1 : n;
}
}
}
}
</script>
</body>
</html>