https://www.browserleaks.com/canvas#how-does-it-work
183836
function (options) {
      var result = []
        // Very simple now, need to make it more complex (geo shapes etc)
      var canvas = document.createElement('canvas')
      canvas.width = 2000
      canvas.height = 200
      canvas.style.display = 'inline'
      var ctx = canvas.getContext('2d')
        // detect browser support of canvas winding
        // http://blogs.adobe.com/webplatform/2013/01/30/winding-rules-in-canvas/
        // https://github.com/Modernizr/Modernizr/blob/master/feature-detects/canvas/winding.js
      ctx.rect(0, 0, 10, 10)
      ctx.rect(2, 2, 6, 6)
      result.push('canvas winding:' + ((ctx.isPointInPath(5, 5, 'evenodd') === false) ? 'yes' : 'no'))
  
      ctx.textBaseline = 'alphabetic'
      ctx.fillStyle = '#f60'
      ctx.fillRect(125, 1, 62, 20)
      ctx.fillStyle = '#069'
        // https://github.com/Valve/fingerprintjs2/issues/66
      if (options.dontUseFakeFontInCanvas) {
        ctx.font = '11pt Arial'
      } else {
        ctx.font = '11pt no-real-font-123'
      }
      ctx.fillText('Cwm fjordbank glyphs vext quiz, \ud83d\ude03', 2, 15)
      ctx.fillStyle = 'rgba(102, 204, 0, 0.2)'
      ctx.font = '18pt Arial'
      ctx.fillText('Cwm fjordbank glyphs vext quiz, \ud83d\ude03', 4, 45)
  
        // canvas blending
        // http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/
        // http://jsfiddle.net/NDYV8/16/
      ctx.globalCompositeOperation = 'multiply'
      ctx.fillStyle = 'rgb(255,0,255)'
      ctx.beginPath()
      ctx.arc(50, 50, 50, 0, Math.PI * 2, true)
      ctx.closePath()
      ctx.fill()
      ctx.fillStyle = 'rgb(0,255,255)'
      ctx.beginPath()
      ctx.arc(100, 50, 50, 0, Math.PI * 2, true)
      ctx.closePath()
      ctx.fill()
      ctx.fillStyle = 'rgb(255,255,0)'
      ctx.beginPath()
      ctx.arc(75, 100, 50, 0, Math.PI * 2, true)
      ctx.closePath()
      ctx.fill()
      ctx.fillStyle = 'rgb(255,0,255)'
        // canvas winding
        // http://blogs.adobe.com/webplatform/2013/01/30/winding-rules-in-canvas/
        // http://jsfiddle.net/NDYV8/19/
      ctx.arc(75, 75, 75, 0, Math.PI * 2, true)
      ctx.arc(75, 75, 25, 0, Math.PI * 2, true)
      ctx.fill('evenodd')
  
      if (canvas.toDataURL) { result.push('canvas fp:' + canvas.toDataURL()) }
      return result
    }
814179
function (ctx, scale, layers, styles, zoom, minX, maxX, minY) {
  // background first
  styles.forEach(function(style) {
    if (cartoSelectorIsMatch(style, null, null, zoom)) {
      style.rules.forEach(function(rule) {
        if (rule.name === "background-color") {
          ctx.fillStyle = rule.value.toString();
        }
        else if (rule.name === "background-image") {
          if (!(rule.value instanceof Canvas.Image)) {
            var content = rule.value.toString();
            var img = new Canvas.Image();
            var imagePath = path.normalize(__dirname + "/../static/images/" + content);
            img.src = fs.readFileSync(imagePath);
            rule.value = img;
          }
        
          img = rule.value;
          ctx.fillStyle = ctx.createPattern(img, "repeat");
        }
      });
      ctx.fillRect(0,0,ctx.canvas.width, ctx.canvas.height);
    }
  });
  
  // create list of attachments (in order) so that we can walk through and render them together for each layer
  // TODO: should be able to do this as part of the processing stage
  var attachments = styles.reduce(function(attachmentList, style) {
    if (style.attachment !== "__default__" && attachmentList.indexOf(style.attachment) === -1) {
      attachmentList.push(style.attachment);
    }
    return attachmentList;
  }, []);
  attachments.push("__default__");
  
  layers.forEach(function(layer, i) {
    var source = layer.source;
    var features = layer.features || layer;
    
    attachments.forEach(function(attachment) {
      
      features.forEach(function(feature) {
        // get all the drawing rules for this attachment and feature
        var collapsedStyle = {};
        var instanceOrder = [];
        styles.forEach(function(style) {
          if (style.attachment === attachment && cartoSelectorIsMatch(style, feature, source, zoom)) {
            style.rules.forEach(function(rule) {
              if (!collapsedStyle[rule.instance]) {
                collapsedStyle[rule.instance] = {};
                instanceOrder.push(rule.instance);
              }
              if (!collapsedStyle[rule.instance].hasOwnProperty(rule.name)) {
                collapsedStyle[rule.instance][rule.name] = rule.value;
              }
            });
          }
        });
        
        var renderInstance = function(instanceName) {
          var instanceStyle = collapsedStyle[instanceName];
          
          ctx.save();
  
          var shouldFill = false,
              shouldStroke = false,
              shouldMark = false,
              shouldPoint = false,
              shouldText = false,
              dashedStroke = false;
          for (var key in instanceStyle) {
            var rawValue = instanceStyle[key],
                value = rawValue.toString();
            
            if (key === "background-color" || key === "polygon-fill") {
              ctx.fillStyle = value;
              shouldFill = true;
            }
            else if (key === "background-image" || key === "polygon-pattern-file") {
              if (rawValue) {
                ctx.fillStyle = ctx.createPattern(rawValue, "repeat");
                shouldFill = true;
              }
            }
            else if (key === "line-width") {
              ctx.lineWidth = parseInt(value);
            }
            else if (key === "line-color") {
              ctx.strokeStyle = value;
              shouldStroke = true;
            }
            else if (key === "line-opacity") {
              // handled at stroke time below
            }
            else if (key === "line-join") {
              ctx.lineJoin = value;
            }
            else if (key === "line-cap") {
              ctx.lineCap = value;
            }
            else if (key === "line-miterlimit") {
              ctx.miterLimit = value;
            }
            else if (key === "line-dasharray") {
              // TODO: dasharray support
              // console.log("Dasharray: ", value);
              var dashedStroke = value.split(",").map(parseFloat);
              // console.log("    now: ", dashArray);
              // ctx.dash = dashArray;
              // ctx.lineDash = dashArray;
            }
            else if (key === "polygon-opacity") {
              // handled at fill time below
            }
            else if (key === "line-pattern-file") {
              if (rawValue) {
                ctx.strokeStyle = ctx.createPattern(rawValue, "repeat");
                shouldStroke = true;
              }
            }
            else if (key.indexOf("marker") === 0) {
              shouldMark = true;
            }
            else if (key === "point-file") {
              shouldPoint = true;
            }
            else if (key === "text-name") {
              shouldText = true;
            }
          }
          
          if (shouldFill || shouldStroke || shouldMark || shouldPoint || shouldText) {
            ctx.beginPath();
            var shape = feature.geometry || feature;
            var coordinates = shape.coordinates;
            renderPath[shape.type].call(ctx, coordinates, scale);
            if (shouldFill) {
              ctx.globalAlpha = parseFloat(instanceStyle["polygon-opacity"]) || 1.0;
              var fillColor = instanceStyle["polygon-fill"];
              var fillPattern = instanceStyle["polygon-pattern-file"]
              if (fillColor) {
                ctx.fillStyle = fillColor.toString();
                ctx.fill();
              }
              if (fillPattern) {
                ctx.fillStyle = ctx.createPattern(fillPattern, "repeat");;
                ctx.fill();
              }
            }
            if (shouldStroke) {
              ctx.globalAlpha = parseFloat(instanceStyle["line-opacity"]) || 1.0;
              if (dashedStroke) {
                // since canvas doesn't yet have dashed line support, we have to draw a dashed path :(
                ctx.closePath();
                ctx.beginPath();
                renderDashedPath[shape.type].call(ctx, dashedStroke, coordinates);
              }
              ctx.stroke();
            }
            ctx.closePath();
            
            if (shouldMark) {
              if (instanceStyle["marker-file"]) {
                renderImage[shape.type].call(ctx, instanceStyle["marker-file"], coordinates);
              }
              else {
                // we only support the "ellipse" type
                // we only support circles, not ellipses right now :\
                var radius = instanceStyle["marker-width"] || instanceStyle["marker-height"];
                radius = (radius ? radius.value : 10) / 2;

                var shouldFillMarker = false;
                var shouldStrokeMarker = false;
                if (instanceStyle["marker-fill"]) {
                  ctx.fillStyle = instanceStyle["marker-fill"].toString();
                  shouldFillMarker = true;
                }
                if (instanceStyle["marker-line-color"]) {
                  ctx.strokeStyle = instanceStyle["marker-line-color"].toString();
                  shouldStrokeMarker = true;
                }
                if (instanceStyle["marker-line-width"]) {
                  var lineWidth = instanceStyle["marker-line-width"].value;
                  ctx.lineWidth = lineWidth;
                  shouldStrokeMarker = !!lineWidth;
                }
                
                ctx.beginPath();
                renderDot[shape.type].call(ctx, radius, coordinates);
                if (shouldFillMarker) {
                  ctx.fill();
                }
                if (shouldStrokeMarker) {
                  ctx.stroke();
                }
                ctx.closePath();
              }
            }
            
            if (shouldPoint && instanceStyle["point-file"]) {
              renderImage[shape.type].call(ctx, instanceStyle["point-file"], coordinates);
            }
            
            if (shouldText) {
              var text = instanceStyle["text-name"];
              if (text.is === "propertyLookup") {
                text = text.toString(feature);
              }
              
              if (text) {
                var textSize = (instanceStyle["text-size"] || "10").toString();
                var textFace = (instanceStyle["text-face-name"] || "sans-serif").toString();
                ctx.font = textSize + "px '" + textFace + "'";
                
                var textInfo = {
                  text: text
                };
                
                // offsetting
                textInfo.offset = {
                  x: instanceStyle["text-dx"] ? instanceStyle["text-dx"].value : 0,
                  y: instanceStyle["text-dy"] ? instanceStyle["text-dy"].value : 0
                };
                
                // vertical alignment
                var verticalAlign = instanceStyle["text-vertical-alignment"];
                if (verticalAlign && verticalAlign.value !== "auto") {
                  ctx.textBaseline = {
                    top: "top",
                    middle: "middle",
                    bottom: "alphabetic"
                  }[verticalAlign];
                }
                else {
                  ctx.textBaseline = textInfo.offset.y === 0 ? "middle" : (textInfo.offset.y < 0 ? "top" : "alphabetic");
                }
                
                // horizontal alignment
                var textHorizontalAlignment = instanceStyle["text-horizontal-alignment"];
                if (textHorizontalAlignment) {
                  ctx.textAlign = textHorizontalAlignment.toString();
                }
                else {
                  // default to center
                  ctx.textAlign = "center";
                }
                textInfo.align = ctx.textAlign;
                
                // text-transform
                var textTransform = instanceStyle["text-transform"];
                textTransform = textTransform && textTransform.toString();
                if (textTransform === "uppercase") {
                  textInfo.text = text.toUpperCase();
                }
                if (textTransform === "lowercase") {
                  textInfo.text = text.toLowerCase();
                }
                if (textTransform === "capitalize") {
                  textInfo.text = text.replace(/\b(\w)/g, function(match, character) {
                    return character.toUpperCase();
                  });
                }
                
                // text-placement
                var placement = instanceStyle["text-placement"];
                textInfo.placement = placement ? placement.toString() : "point";
                
                // TODO: text-placement-type (currently like "dummy")
                // TODO: text-align (this is alignment within the text *box*)
                // We don't have anything that generates a box right now, so we dont' support this
                
                if (instanceStyle["text-halo-fill"]) {
                  ctx.strokeStyle = instanceStyle["text-halo-fill"].toString();
                  if (instanceStyle["text-halo-radius"]) {
                    ctx.lineWidth = instanceStyle["text-halo-radius"].value * 2;
                  }
                  
                  // definitely DON'T leave this set to miter :P
                  ctx.lineJoin = "round";
                  textInfo.stroke = true;
                  renderText[shape.type].call(ctx, textInfo, coordinates);
                }
              
                if (instanceStyle["text-fill"]) {
                  ctx.fillStyle = instanceStyle["text-fill"].toString();
                }
                
                textInfo.stroke = false;
                renderText[shape.type].call(ctx, textInfo, coordinates);
              }
            }
          }
          
          ctx.restore();
        };
      
        instanceOrder.forEach(function(instanceName) {
          if (instanceName !== "__default__") {
            renderInstance(instanceName);
          }
        });
      
        if (collapsedStyle["__default__"]) {
          renderInstance("__default__");
        }
      
      });
      
    });
  });
}
308107
function() {
        var c = this._canvas;
        c.width = Crafty.viewport.width;
        c.height = Crafty.viewport.height;

        var gl = this.context;
        gl.viewportWidth = c.width;
        gl.viewportHeight = c.height;
    }
1174184
function() {
      WireIt.CanvasContainer.superclass.render.call(this);

		this.canvasEl = new WireIt.CanvasElement(this.bodyEl);
		this.canvasEl.SetCanvasRegion(0,0, this.width, this.height );
		this.canvasWidth = this.width;
		this.canvasHeight = this.height;
		this.drawCanvas();
   }
458924
function (opt) {
    var cap = new Captcha(opt);
    cap.use(drawBackground);
    cap.use(drawLines);
    cap.use(drawText);
    cap.use(drawLines);
    return cap;
  }
653114
protected function canvasSpacingX()
    {
        $this->canvas['spacing']['x'] = 0;

        if ($this->intermediate['width'] < $this->canvas['width']) {
            $difference = $this->canvas['width'] - $this->intermediate['width'];

            if ($difference % 2 === 0) {
                $this->canvas['spacing']['x'] = $difference / 2;
            } else {
                if ($difference > 1) {
                    $this->canvas['spacing']['x'] = ($difference - 1) / 2 + 1;
                } else {
                    $this->canvas['spacing']['x'] = 1;
                }
            }
        }
    }
1372010
function drawVideo(video) {
			if (video.paused || video.ended || _stop) {
				return false;
			}
			//nasty hack for FF webcam (Thanks to Julian Ćwirko, kontakt@redsunmedia.pl)
			try {
				_context.clearRect(0, 0, _w, _h);
				_context.drawImage(video, 0, 0, _w, _h);
			} catch(e) {

			}
			_drawTimeout = setTimeout(drawVideo, animation.duration, video);
			link.setIcon(_canvas);
		}
328617
function getCanvas(canvas, name){
      if(!canvas){
        canvas = D.create('canvas');
        if (typeof FlashCanvas != "undefined" && typeof canvas.getContext === 'function') {
          FlashCanvas.initElement(canvas);
          this.isFlashCanvas = true;
        }
        canvas.className = 'flotr-'+name;
        canvas.style.cssText = 'position:absolute;left:0px;top:0px;';
        D.insert(el, canvas);
      }
      _.each(size, function(size, attribute){
        D.show(canvas);
        if (name == 'canvas' && canvas.getAttribute(attribute) === size) {
          return;
        }
        canvas.setAttribute(attribute, size * o.resolution);
        canvas.style[attribute] = size + 'px';
      });
      canvas.context_ = null; // Reset the ExCanvas context
      return canvas;
    }
457666
def html(args = {})
      id     = SecureRandom.uuid
      width  = args[:width]  || "50"
      config = args[:config] || @config.json
      type   = @config.type

      "<div id=\"canvas-holder\" style=\"width:#{width}%\">
        <canvas id=\"#{id}\" />
      </div>
      <script>
        var config = #{config}
        window.onload = function() {
          var ctx = document.getElementById(\"#{id}\").getContext(\"2d\");
          new Chart(ctx, config);
        };
      </script>" 
    end
233155
function urlMatch (asset, pattern) {
  var multi = pattern.split(',')
  var re

  if (multi.length > 1) {
    for (var i = 0, len = multi.length; i < len; i++) {
      re = new RegExp(multi[i].replace(/([.?+^$[\]\\(){}|/-])/g, '\\$1').replace(/\*/g, '.*'))
      if (re.test(asset)) {
        return true
      }
    }
    return false
  }

  re = new RegExp(pattern.replace(/([.?+^$[\]\\(){}|/-])/g, '\\$1').replace(/\*/g, '.*'))
  return re.test(asset)
}
285618
function(src) {
	var canvas = document.createElement('canvas'),
		ctx = canvas.getContext('2d'),
		imgObj = new Image();
	
	imgObj.src = src;
	canvas.width = imgObj.width;
	canvas.height = imgObj.height; 
	
	ctx.drawImage(imgObj, 0, 0); 
	var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);

	for(var y = 0; y < imgPixels.height; y++){
		for(var x = 0; x < imgPixels.width; x++){
			var i = (y * 4) * imgPixels.width + x * 4;
			var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
			imgPixels.data[i] = avg; 
			imgPixels.data[i + 1] = avg; 
			imgPixels.data[i + 2] = avg;
		}
	}
	
	ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
	return canvas.toDataURL();
}
28994
def _updateCanvasDraw(self):
        
        fn = self.canvas.draw
        def draw2(*a,**k):
            self._updateGridSpec()
            return fn(*a,**k)
        self.canvas.draw = draw2
41169
function drawChatIn() {
    $(CHATIN).show();
    function submit() {
        var chatin = $(CHATIN+"> input")[0].value;
        if (!CHATRE.test(chatin)) {
            if(chatin) {
                alert("Your input text is too long!");
            }
            return false;
        }
        var game = $.cookie("game");
        var resource;
        if (game) {
            resource = "/games/" + enc(game) + "/chat";
        } else {
            resource = "/chat";
        }
        $.post(resource, {
            input: chatin,
            name: $.cookie("player")
        }, function() {
            $(CHATIN+"> input").val('');  // post was succesful, so clear input
            drawChatLog();
        });
    }
    $(CHATIN+"> button").click(submit);
    $(CHATIN+"> input:visible").focus();
    $(CHATIN+"> input").keydown(function(event) {
        if (event.keyCode === 13) {
            submit();
        }
    });
}
1373278
function drawMaskingClip() {
            maskingRectangle = svg.selectAll('.chart-group')
              .append('clipPath')
              .attr('id', maskingRectangleId)
                .append('rect')
                .attr('width', chartWidth)
                .attr('height', chartHeight)
                .attr('x', 0)
                .attr('y', 0);
        }
435645
def ruokuai_captcha_handler(self, params, image_url):
        

        headers = {
            'Connection': 'Keep-Alive',
            'Expect': '100-continue',
            'User-Agent': 'ben',
        }
        image_data = requests.get(image_url).content
        files = {'image': ('check_code.png', image_data)}
        r = requests.post(
            'http://api.ruokuai.com/create.json',
            data=params,
            files=files,
            headers=headers
        )
        verify_code_dict = r.json()
        if verify_code_dict:
            if 'Error' in verify_code_dict.keys():
                print (verify_code_dict['Error'])
                return ''
            verify_code = verify_code_dict.get('Result', '')
        else:
            print ('rk failed ', verify_code_dict)
            return ''

        return verify_code
12734
function Canvas( figure ) {

	// INSTANCE ATTRIBUTES //

	this._parent = figure;
	this._root = undefined;
	this._children = {};
	this._config = {
		'width': 500,
		'height': 500,
		"background": false
	};

	// REGISTER //
	if ( figure._config.hasOwnProperty( 'canvas' )  ) {
		figure._config.canvas.push( this._config );
	} else {
		figure._config.canvas = [ this._config ];
	}
	if ( figure._children.hasOwnProperty( 'canvas' ) ) {
		figure._children.canvas.push( this );
	} else {
		figure._children.canvas = [ this ];
	}

	return this;

}
858453
function() {
			this.id = 'jq-signature-canvas-' + (++idCounter);

      // Set up the canvas
      this.$canvas = $(canvasFixture).appendTo(this.$element);
      this.$canvas.attr({
        width: this.settings.width,
        height: this.settings.height
      });
      this.$canvas.css({
        boxSizing: 'border-box',
        width: this.settings.width + 'px',
        height: this.settings.height + 'px',
        border: this.settings.border,
        background: this.settings.background,
        cursor: 'crosshair'
      });
      this.$canvas.attr('id', this.id);

      // Fit canvas to width of parent
      if (this.settings.autoFit === true) {
        this._resizeCanvas();
        // TODO - allow for dynamic canvas resizing
        // (need to save canvas state before changing width to avoid getting cleared)
        // var timeout = false;
        // $(window).on('resize', $.proxy(function(e) {
        //   clearTimeout(timeout);
        //   timeout = setTimeout($.proxy(this._resizeCanvas, this), 250);
        // }, this));
      }
      this.canvas = this.$canvas[0];
      this._resetCanvas();

			// Listen for pointer/mouse/touch events
			// TODO - PointerEvent isn't fully supported, but eventually do something like this:
			// if (window.PointerEvent) {
			// 	this.$canvas.parent().css('-ms-touch-action', 'none');
			// 	this.$canvas.on("pointerdown MSPointerDown", $.proxy(this._downHandler, this));
      //   this.$canvas.on("pointermove MSPointerMove", $.proxy(this._moveHandler, this));
			// 	this.$canvas.on("pointerup MSPointerUp", $.proxy(this._upHandler, this));
      // }
      // else {
      //   this.$canvas.on('mousedown touchstart', $.proxy(this._downHandler, this));
      //   this.$canvas.on('mousemove touchmove', $.proxy(this._moveHandler, this));
      //   this.$canvas.on('mouseup touchend', $.proxy(this._upHandler, this));
      // }
      this.$canvas.on('mousedown touchstart', $.proxy(this._downHandler, this));
      this.$canvas.on('mousemove touchmove', $.proxy(this._moveHandler, this));
      this.$canvas.on('mouseup touchend', $.proxy(this._upHandler, this));

      // Start drawing
      var that = this;
      (function drawLoop() {
        window.requestAnimFrame(drawLoop);
        that._renderCanvas();
      })();
    }