Skip to content

Instantly share code, notes, and snippets.

@weberliu
Created March 7, 2018 08:27
Show Gist options
  • Select an option

  • Save weberliu/ef61a94cbdd0bdd1ed2feb264b36e9a2 to your computer and use it in GitHub Desktop.

Select an option

Save weberliu/ef61a94cbdd0bdd1ed2feb264b36e9a2 to your computer and use it in GitHub Desktop.
It's a bit more complicated to get a cover functionality, though here here is one solution for this:
/**
* https://stackoverflow.com/questions/21961839/simulation-background-size-cover-in-canvas/21961894#21961894
*
* By Ken Fyrstenberg Nilsen
*
* drawImageProp(context, image [, x, y, width, height [,offsetX, offsetY]])
*
* If image and context are only arguments rectangle will equal canvas
*/
function drawImageProp (ctx, img, x, y, w, h, offsetX, offsetY) {
if (arguments.length === 2) {
x = y = 0
w = ctx.canvas.width
h = ctx.canvas.height
}
// default offset is center
offsetX = typeof offsetX === 'number' ? offsetX : 0.5
offsetY = typeof offsetY === 'number' ? offsetY : 0.5
// keep bounds [0.0, 1.0]
if (offsetX < 0) offsetX = 0
if (offsetY < 0) offsetY = 0
if (offsetX > 1) offsetX = 1
if (offsetY > 1) offsetY = 1
var iw = img.width
var ih = img.height
var r = Math.min(w / iw, h / ih)
var nw = iw * r // new prop. width
var nh = ih * r // new prop. height
var cx, cy, cw, ch
var ar = 1
// decide which gap to fill
if (nw < w) ar = w / nw
if (Math.abs(ar - 1) < 1e-14 && nh < h) ar = h / nh // updated
nw *= ar
nh *= ar
// calc source rectangle
cw = iw / (nw / w)
ch = ih / (nh / h)
cx = (iw - cw) * offsetX
cy = (ih - ch) * offsetY
// make sure source rectangle is valid
if (cx < 0) cx = 0
if (cy < 0) cy = 0
if (cw > iw) cw = iw
if (ch > ih) ch = ih
// fill image in dest. rectangle
ctx.drawImage(img, cx, cy, cw, ch, x, y, w, h)
}
@kindlisa
Copy link

kindlisa commented Mar 7, 2018

Hello my name is miss lisa i saw your profile here and i will like to
estabilish a mutual relationship with you please you can contact me through
my private email address (lisaafinebrown@gmail.com) i have something very
important to discuss with you i will be waiting for your response soonest
Thanks yours
Lisa.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment