console
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
for (var x = 0; x < 20; x++) {
for (var y = 0; y < 20; y++) {
context.strokeRect(x * 20, y * 20, 20, 20);
}
}
var normalMap = new Image();
normalMap.src = "http://whxaxes.github.io/canvas-test/src/Funny-demo/transform/img/test.jpg";
normalMap.onload = function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
// 绘制法线贴图并应用到每个小矩形上
for (var x = 0; x < 20; x++) {
for (var y = 0; y < 20; y++) {
var pixelData = context.getImageData(x * 20, y * 20, 1, 1).data;
var normal = [
(pixelData[0] / 255) * 2 - 1,
(pixelData[1] / 255) * 2 - 1,
(pixelData[2] / 255) * 2 - 1
];
// 计算法线贴图在该点上的偏移量
var offset = [
normal[0] * 10,
normal[1] * 10,
normal[2] * 10
];
// 应用法线贴图到矩形
context.save();
context.beginPath();
context.moveTo(x * 20, y * 20);
context.lineTo((x + 1) * 20, y * 20);
context.lineTo((x + 1) * 20 + offset[0], y * 20 + offset[1]);
context.lineTo(x * 20 + offset[0], y * 20 + offset[1]);
context.closePath();
context.clip();
context.drawImage(normalMap, x * 20 - 10, y * 20 - 10, 40, 40);
context.restore();
}
}
};
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>图像3d变形</title>
<style>
body{-moz-user-select: none;}
#cas{
position: absolute;
top: 80px;
left: 0;
right: 0;
margin: auto;
border: 1px solid;
}
.tips{text-align: center;margin: 15px 0;}
.control{ text-align: center; }
</style>
</head>
<body onselectstart="return false">
<canvas id="myCanvas" width="400" height="400"></canvas>
</body>
</html>