1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| <!DOCTYPE html> <html lang="en">
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #canvas { position: absolute; margin: auto; top: 0; bottom: 0; left: 0; right: 0; background: #cccccc } </style> </head>
<body> <canvas id="canvas">您的浏览器不支持canvas,<a href="https://www.google.cn/intl/zh-CN/chrome/">立即升级</a></canvas> <script> var canvas = document.getElementById('canvas') if (canvas.getContext) { var ctx = canvas.getContext('2d') var img = new Image() img.src = "黄晓明.jpg"
img.onload = function () { canvas.width = img.width * 2 canvas.height = img.height ctx.drawImage(this, 0, 0, img.width, img.height)
var mskSize = 8 var imageData = ctx.getImageData(0, 0, img.width, img.height) for (var x = 0; x < img.width; x += mskSize) { for (var y = 0; y < img.height; y += mskSize) { var color = getPointColor(imageData, parseInt(x + Math.random() * mskSize), parseInt(y + Math.random() * mskSize))
for (var a = x, n = 0; n < mskSize; a++ , n++) { for (var b = y, m = 0; m < mskSize; b++ , m++) { setPointColor(imageData, a, b, color) } } } } ctx.putImageData(imageData, img.width + 1, 0) }
function getPointColor(imageData, x, y) { var color = []
var data = imageData.data, w = imageData.width, h = imageData.height var num = y * w + x
color[0] = data[4 * num] color[1] = data[4 * num + 1] color[2] = data[4 * num + 2] color[3] = data[4 * num + 3]
return color }
function setPointColor(imageData, x, y, color) { var data = imageData.data, w = imageData.width, h = imageData.height var num = y * w + x data[4 * num] = color[0] data[4 * num + 1] = color[1] data[4 * num + 2] = color[2] data[4 * num + 3] = color[3] } } </script> </body>
</html>
|