在工作钟遇到一个前台给图片部分打码的功能,绞尽奶汁没想到什么好办法。后来发现canvas可以模拟出这个效果。现在贴上代码。
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
body {
background: #ccc;
}
canvas {
background: #fff;
}
</style>
</head>
<body>
<canvas width="800" height="400" id="canvas">
<span>亲,您的浏览器不支持canvas,换个浏览器试试吧!</span>
</canvas>
</body>
<script>
window.onload = function () {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var aImg = new Image();
aImg.src = 'img/IMG_1949.JPG';//这里放自己的图片
aImg.onload = function () {
draw(this);
}
function draw(obj) {
//绘制第一张图
ctx.drawImage(obj, 0, 0, 400, 400);
//绘制第二张图,用作对比
ctx.drawImage(obj, 400, 0, 400, 400);
//获取坐边图像的局部坐标的部分像素。设置马赛克的模程度
var oImg = ctx.getImageData(550, 100, 150, 150);
var w = oImg.width;
var h = oImg.height;
//马赛克的程度,数字越大越模糊
var num = 10;
//等分画布
var stepW = w / num;
var stepH = h / num;
//这里是循环画布的像素点
for (var i = 0; i < stepH; i++) {
for (var j = 0; j < stepW; j++) {
//获取一个小方格的随机颜色,这是小方格的随机位置获取的
var color = getXY(oImg, j * num + Math.floor(Math.random() * num), i * num + Math.floor(Math.random() * num));
//这里是循环小方格的像素点,
for (var k = 0; k < num; k++) {
for (var l = 0; l < num; l++) {
//设置小方格的颜色
setXY(oImg, j * num + l, i * num + k, color);
}
}
}
}
ctx.putImageData(oImg, 550, 100);//打码的位置
}
function getXY(obj, x, y) {
var w = obj.width;
var h = obj.height;
var d = obj.data;
var color = [];
color[0] = obj.data[4 * (y * w + x)];
color[1] = obj.data[4 * (y * w + x) + 1];
color[2] = obj.data[4 * (y * w + x) + 2];
color[3] = obj.data[4 * (y * w + x) + 3];
return color;
}
function setXY(obj, x, y, color) {
var w = obj.width;
var h = obj.height;
var d = obj.data;
obj.data[4 * (y * w + x)] = color[0];
obj.data[4 * (y * w + x) + 1] = color[1];
obj.data[4 * (y * w + x) + 2] = color[2];
obj.data[4 * (y * w + x) + 3] = color[3];
}
}
</script>
</html>
效果如下图所示。测试浏览器为谷歌浏览器。

1540

被折叠的 条评论
为什么被折叠?



