Skip to content

Instantly share code, notes, and snippets.

@moimikey
Created August 6, 2014 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moimikey/92a5800bf1e39958b7e4 to your computer and use it in GitHub Desktop.
Save moimikey/92a5800bf1e39958b7e4 to your computer and use it in GitHub Desktop.
# Converts a data image uri to canvas image
#
# reader = new FileReader()
# reader.onload = (evt) =>
# App.Util.dataToCanvas evt, el: @ui.thumb, width: 80, height: 40
# reader.readAsDataURL(...)
#
# @ui.thumb = jquery selector
# ultimately the jquery dependency can be 86ed from this...
#
Util.dataToCanvas = (evt, options={}) ->
{el, width, height} = options
img = $('<img>', src: evt.target.result)
canvas = $(el)[0]
context = canvas.getContext('2d')
context.filter = 'best'
context.antialias = 'subpixel'
context.imageSmoothingEnabled = true
context.webkitImageSmoothingEnabled = true
context.mozImageSmoothingEnabled = true
img.load ->
scaled = Util.scaleProportion(width, height, @width, @height)
canvas.setAttribute 'width', width
canvas.setAttribute 'height', height
context.drawImage this,
(canvas.width / 2 - scaled.width / 2),
(canvas.height / 2 - scaled.height / 2),
scaled.width,
scaled.height
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment