使用canvas画图片的点阵
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML龙</title>
<style type="text/css">
html,body{
margin: 0;
padding: 0;
background: #333;
}
.bubble
{
position: absolute;
animation-timing-function: linear;
animation-name: floating;
animation-iteration-count: infinite;
}
@keyframes floating
{
0%{
transform: translateY(0px);
}
50%{
transform: translateY(-5px);
}
100%{
transform: translateY(0px);
}
}
</style>
<script type="text/javascript">
window.onload=function(){
init();
}
function init(){
drawDragonImageInCanvas();
}
function drawDragonImageInCanvas(cb){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var image = new Image();//使用的new方法拉实现
// console.log(image);
image.src = "dragon.jpg";
image.onload = function(){
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image,0,0);
var imageData = ctx.getImageData(0,0,image.width,image.height).data;
// console.log(image.width);
// console.log(image.height);
ctx.clearRect(0,0,image.width,image.height);
var gap = 10;
var dragonContainer = document.getElementById("container");
var dragonScale = 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 bubble = document.createElement("img");
bubble.src = "bubble.png";
bubble.setAttribute("class","bubble");
var bubbleSize = Math.random()*10+20;
bubble.style.left = (w*dragonScale-bubbleSize/2) + "px";
bubble.style.top = (h*dragonScale-bubbleSize/2) + "px";
bubble.style.width = bubble.style.height = bubbleSize+"px";
bubble.style.animationDuration = Math.random()*6+4 + "s";
dragonContainer.appendChild(bubble);
}
}
}
}
}
</script>
</head>
<body>
<div id='container' style="width: 100%;height: 100%;position: absolute;z-index: 2;"></div>
<canvas id='canvas' style="position: absolute;z-index: 1;filter: blur(5px);"></canvas>
</body>
</html>


图片自己下载,然后把代码里面的路径修改一下。
注意
调用getImageData()报跨域的错误,原因是图片存储在本地时,是默认没有域名的,用getImageData方法时,浏览器会判定为跨域而报错。
使用VsCode,下载一个叫 Live Server 的插件

浙公网安备 33010602011771号