1 function draw(id){ 2 var canvas = document.getElementById(id); 3 if(canvas == null){ 4 return false; 5 } 6 var context = canvas.getContext("2d"); 7 8 var imageData = context.createImageData(500,500); 9 var pixels = imageData.data; 10 11 // 马赛克的个数 12 var numTileRows = 4; 13 var numTileCols = 4; 14 15 // 每个块的尺寸 16 var tileWidth = imageData.width / numTileCols; 17 var tileHeight = imageData.height / numTileRows; 18 19 for(var r = 0; r < numTileRows; r++){ 20 for(var c = 0; c < numTileCols; c++){ 21 22 /*var arr = [0,1],round = arr[Math.round(Math.random())]*255; 23 var red = Math.floor(round);// red 24 var green = Math.floor(round);// green 25 var blue = Math.floor(round);// blue*/ 26 var red = Math.floor(Math.random()*255);// red 27 var green = Math.floor(Math.random()*255);// green 28 var blue = Math.floor(Math.random()*255);// blue 29 30 for(var tr = 0; tr < tileHeight; tr++){ 31 for(var tc = 0; tc < tileWidth; tc++){ 32 // 真实坐标 33 var trueX = c * tileWidth + tc; 34 var trueY = r * tileHeight + tr; 35 36 var pos = trueY * imageData.width * 4 + trueX * 4;// 计算索引 37 pixels[pos] = red; 38 pixels[pos + 1] = green; 39 pixels[pos + 2] = blue; 40 pixels[pos + 3] = 255; 41 } 42 } 43 } 44 } 45 context.putImageData(imageData, 0, 0); 46 } 47 48 draw("myCanvas");