首页
登录 | 注册

【canvas马赛克效果】根据加载的图片动态生成对应的马赛克图片

马赛克效果的主要js

close-pixelate.js

/*!
 * Close Pixelate v2.0.00 beta
 * http://desandro.com/resources/close-pixelate/
 * 
 * Developed by
 * - David DeSandro  http://desandro.com
 * - John Schulz  http://twitter.com/jfsiii
 * 
 * Licensed under MIT license
 */

/*jshint asi: true, browser: true, eqeqeq: true, forin: false, immed: false, newcap: true, noempty: true, strict: true, undef: true */

( function( window, undefined ) {


// util vars
var TWO_PI = Math.PI * 2
var QUARTER_PI = Math.PI * 0.25

// utility functions
function isArray( obj ) {
  return Object.prototype.toString.call( obj ) === "[object Array]"
}

function isObject( obj ) {
  return Object.prototype.toString.call( obj ) === "[object Object]"
}

var console = window.console

// check for canvas support
var canvas = document.createElement('canvas')
var isCanvasSupported = canvas.getContext && canvas.getContext('2d')

// don't proceed if canvas is no supported
if ( !isCanvasSupported ) {
  return
}


function ClosePixelation( img, options ) {
  this.img = img
  // creat canvas
  var canvas = this.canvas = document.createElement('canvas')
  this.ctx = canvas.getContext('2d')
  // copy attributes from img to canvas
  canvas.className = img.className
  canvas.id = img.id

  this.render( options )

  // replace image with canvas
  img.parentNode.replaceChild( canvas, img )

}

ClosePixelation.prototype.render = function( options ) {
  this.options = options
  // set size

  var w0 = this.width0 = this.canvas.width = this.img.width;
  var h0 = this.height0 = this.canvas.height = this.img.height;
  
  var w1 = this.width1 = 274;
  var h1 = this.height1 = 274 * this.img.height / this.img.width;  
  
  // draw image on canvas
  this.ctx.drawImage( this.img, 0, 0, w1, h1 )//如果需要将图片设定为特定大小,用这句
	// this.ctx.drawImage( this.img, 0, 0 )//否则用这句

 // get imageData try {
	this.imgData = this.ctx.getImageData( 0, 0, w1, h1 ).data//如果需要将图片设定为特定大小,用这句
	// this.imgData = this.ctx.getImageData( 0, 0, w0, h0 ).data//否则用这句

 } catch ( error ) {
	if ( console ) {
		console.error( error ) 
	}
	return 
}
	this.ctx.clearRect( 0, 0, w1, h1 )
	for ( var i=0, len = options.length; i < len; i++ ) {
		this.renderClosePixels( options[i] ) 
	}
}

ClosePixelation.prototype.renderClosePixels = function( opts ) {

//如果需要将图片设定为特定大小,用这句


 var w = this.width1 var h = this.height1

//否则用这句

// var w = this.width0
//  var h = this.height0

   var ctx = this.ctx
  var imgData = this.imgData

  // option defaults
  
  var res = opts.resolution || 16
  var size = opts.size || res
  
  var alpha = opts.alpha || 1
  var offset = opts.offset || 0
  var offsetX = 0
  var offsetY = 0
  var cols = w / res + 1
  var rows = h / res + 1  
  var halfSize = size / 2
  var diamondSize = size / Math.SQRT2
  var halfDiamondSize = diamondSize / 2

  if ( isObject( offset ) ){ 
    offsetX = offset.x || 0
    offsetY = offset.y || 0
  } else if ( isArray( offset) ){
    offsetX = offset[0] || 0
    offsetY = offset[1] || 0
  } else {
    offsetX = offsetY = offset
  }

  var row, col, x, y, pixelY, pixelX, pixelIndex, red, green, blue, pixelAlpha

  for ( row = 0; row < rows; row++ ) {
    y = ( row - 0.5 ) * res + offsetY
    // normalize y so shapes around edges get color
    pixelY = Math.max( Math.min( y, h-1), 0)

    for ( col = 0; col < cols; col++ ) {
      x = ( col - 0.5 ) * res + offsetX
      // normalize y so shapes around edges get color
      pixelX = Math.max( Math.min( x, w-1), 0)
	  
      pixelIndex = ( pixelX + pixelY * w ) * 4
	  
      red   = imgData[ pixelIndex + 0 ]
      green = imgData[ pixelIndex + 1 ]
      blue  = imgData[ pixelIndex + 2 ]
      pixelAlpha = alpha * ( imgData[ pixelIndex + 3 ] / 255)

      ctx.fillStyle = 'rgba(' + red +','+ green +','+ blue +','+ pixelAlpha + ')'

      switch ( opts.shape ) {
        case 'circle' :
          ctx.beginPath()
            ctx.arc ( x, y, halfSize, 0, TWO_PI, true )
            ctx.fill()
          ctx.closePath()
          break
        case 'diamond' :
          ctx.save()
            ctx.translate( x, y )
            ctx.rotate( QUARTER_PI )
            ctx.fillRect( -halfDiamondSize, -halfDiamondSize, diamondSize, diamondSize )
          ctx.restore()
          break
        default :
          // square
          ctx.fillRect( x - halfSize, y - halfSize, size, size )
      } // switch
    } // col
  } // row
}

// enable img.closePixelate
HTMLImageElement.prototype.closePixelate = function ( options ) {
  return new ClosePixelation( this, options )
}

// put in global namespace
window.ClosePixelation = ClosePixelation

})( window );


然后html中

<img src="4.jpg" id="dolly1" />
<script type="text/javascript" src="close-pixelate.js"></script>
<script type="text/javascript">
	window.onload = function() {
	  var dolly1 = document.getElementById('dolly1')
	  var pixelOpts = [ { resolution: 8 } ]//,shape:'diamond',shape:'circle' //默认为方形马赛克效果,还有钻石(菱形)和圆形马赛克可选,马赛克大小这里为8
	  var pixelDolly1 = dolly1.closePixelate( pixelOpts )
        }
 </script>




2020 jeepxie.net webmaster#jeepxie.net
10 q. 0.008 s.
京ICP备10005923号