canvas实现将文字变成颗粒

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>粒子字体效果</title>
<style>
html,
body {
margin: 0;
100%;
height: 100%;
}

button {
position: absolute;
top: 0;
left: 0;
}
</style>
</head>

<body>

<canvas id="myCanvas" style="background:black; ">
您的浏览器不支持 HTML5 canvas 标签。
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var winWidth = 0;
var winHeight = 0;
findDimensions()

function findDimensions() //函数:获取尺寸
{
//获取窗口宽度
if (window.innerWidth)
winWidth = window.innerWidth;
else if ((document.body) && (document.body.clientWidth))
winWidth = document.body.clientWidth;
//获取窗口高度
if (window.innerHeight)
winHeight = window.innerHeight;
else if ((document.body) && (document.body.clientHeight))
winHeight = document.body.clientHeight;
//通过深入Document内部对body进行检测,获取窗口大小
if (document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth) {
winHeight = document.documentElement.clientHeight;
winWidth = document.documentElement.clientWidth;
}

c.height = winHeight;
c.width = winWidth;
getpoint('WWW.JUSUKEJI.COM');
// drawrect()
}



//调用函数,获取数值
window.onresize = findDimensions;
//–>
function createRect(gx, gy) { //设置小方块对象的属性,然后生成小方块
this.x = c.width * Math.random();
this.y = c.height * Math.random();
this.v = Math.random() * 4 - 2;
this.w = ~~(Math.random() * 2 + 2);
this.h = ~~(Math.random() * 2 + 2);
this.color = ['#ffff33', '#ff00cc', '#00ffff', '#9933ff'];
this.gx = gx;
this.gy = gy;

}
createRect.prototype = {

draw: function () {

// ctx.clearRect(0,0,c.width,c.height);
ctx.beginPath();
ctx.fillStyle = this.color[~~(Math.random() * 4)];
console.log()
console.log(this.x - this.w, this.y - this.h, this.w, this.h)
ctx.fillRect(this.x - this.w, this.y - this.h, this.w, this.h);
ctx.fill()
},
move: function () {

}

}


function drawrect() {
for (var i = 0; i < 500; i++) {
var rect = new createRect()
rect.draw()

}

}

function getpoint(txt) {


ctx.clearRect(0, 0, c.width, c.height);
ctx.fillStyle = "black";

ctx.font = "100px blod";

ctx.fillText(txt, c.width / 2 - ctx.measureText(txt).width / 2, c.height / 2);
// ctx.closePath()
var imgData = ctx.getImageData(0, 0, c.width - ctx.measureText(txt).width / 2, c.height);
for (var x = 0; x < imgData.width; x += 4) {
for (var y = 0; y < imgData.height; y += 4) {
var i = (imgData.width * y + x) * 4;
// console.log(x,y)
if (imgData.data[i + 3] > 0) {
// drawrect(10,20)
ctx.beginPath();
ctx.fillStyle = 'red'
ctx.fillRect(x - 2, y - 2, 2, 2);
ctx.fill()
}
}
}
// ctx.putImageData(imgData,10,70);
}



getpoint('WWW.JUSUKEJI.COM');
drawrect()

// setInterval(drawrect,30)
</script>


</body>

</html>
原文地址:https://www.cnblogs.com/zzh965390267/p/8249765.html