canvas基础—04像素之马赛克

电玩女神 2022-03-19 15:24 363阅读 0赞

demo.html

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>canvas学习</title>
  6. <style>
  7. body{background: black;color:white;font-size:30px;}
  8. #c1{background: white}
  9. span{color: white}
  10. </style>
  11. <script type="text/javascript">
  12. window.onload = function(){
  13. var oC = document.getElementById('c1')
  14. var oGC = oC.getContext('2d')
  15. var yImg = new Image()
  16. yImg.onload = function(){
  17. draw(this)
  18. }
  19. yImg.src = '1.png'
  20. function draw(obj) {
  21. oC.width = obj.width
  22. oC.height = obj.height * 2
  23. oGC.drawImage(obj,0,0) // drawImage(oImg,x,y,w,h)
  24. var oImg = oGC.getImageData(0,0,obj.width,obj.height)//获取图像数据(x,y,w,h)
  25. var w = oImg.width //图片一行的个数
  26. var h = oImg.height //图片一列的个数
  27. //***
  28. var newImage = oGC.createImageData(obj.width,obj.height)//createImageData(w,h)生成新的像素矩阵
  29. var stepW = Math.floor(w/10)
  30. var stepH = Math.floor(h/10)
  31. for(var i = 0;i<stepH;i++){ //每一行
  32. for(var j = 0;j<stepW;j++){ //每一列
  33. // 随机取某一个区域的颜色
  34. var color = getXY(oImg,j*10+Math.floor(Math.random()*10),i*10+Math.floor(Math.random()*10))
  35. // 该区域所有的颜色都要变成这个颜色值
  36. for(var k =0;k<10;k++){
  37. for(var l=0;l<10;l++){
  38. setXY(newImage,j*10+l,i*10+k,color)
  39. }
  40. }
  41. }
  42. }
  43. oGC.putImageData(newImage,0,obj.height)
  44. }
  45. // 返回该像素点的颜色
  46. function getXY(obj,x,y) {
  47. var w =obj.width //100
  48. var h = obj.height //100
  49. var d = obj.data
  50. var color = []
  51. color[0] = d[4*(y*w+x)] //4(y*w+x)的结果是算出这一行以前的所有值,假设是一个10*10就好理解
  52. color[1] = d[4*(y*w+x)+1]
  53. color[2] = d[4*(y*w+x)+2]
  54. color[3] = d[4*(y*w+x)+3]
  55. return color
  56. }
  57. function setXY(obj,x,y,color){
  58. var w =obj.width //100
  59. var h = obj.height //100
  60. var d = obj.data
  61. d[4*(y*w+x)] = color[0] //4(y*w+x)的结果是算出这一行以前的所有值,假设是一个10*10就好理解
  62. d[4*(y*w+x)+1] = color[1]
  63. d[4*(y*w+x)+2] = color[2]
  64. d[4*(y*w+x)+3] = color[3]
  65. }
  66. }
  67. </script>
  68. </head>
  69. <body>
  70. <canvas id="c1" width="1000" height="1000">
  71. <span>不支持canvas浏览器</span>
  72. </canvas>
  73. </body>
  74. </html>

效果

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2ppYW9qc3Vu_size_16_color_FFFFFF_t_70

发表评论

表情:
评论列表 (有 0 条评论,363人围观)

还没有评论,来说两句吧...

相关阅读