javascript - How to make a HTML5 canvas fit dynamic parent/flex box container -
is there way can create canvas inside dynamic re-sizing flex-box container?
preferably css solution think javascript required redraw?
i think 1 solution listen re-sizing event , scale canvas meet size of flex box parent force redraw preferably use css possible or more clean/less code solution.
the current approach css based canvas re-sized according parent flex box element. graphics blurred, re positioned , overflowed canvas in below screenshot.
css:
html,body{ margin:0; width:100%; height:100%; } body{ display:flex; flex-direction:column; } header{ width:100%; height:40px; background-color:red; } main{ display:flex; flex: 1 1 auto; border: 1px solid blue; width:80vw; } canvas{ flex: 1 1 auto; background-color:black; }
html:
<header> </header> <main> <canvas id="stage"></canvas> </main>
javascript:
$( document ).ready(function() { var ctx = $("#stage")[0].getcontext("2d"); ctx.strokestyle="#ffffff"; ctx.beginpath(); ctx.arc(100,100,50,0,2*math.pi); ctx.stroke(); });
js fiddle showing issue: https://jsfiddle.net/h2v1w0a1/
think of canvas image. if scale different size original appear blurry @ point, , perhaps on depending on interpolation algorithm chosen browser. canvas browser tend chose bi-linear on bi-cubic there higher risk of blur actual image.
you want have things in canvas rendered sharp possible , way adapt size parent using javascript, , avoid css (the latter things printing, or when need "retina resolutions").
to parent container size in pixels can use getcomputedstyle()
(see update below):
var parent = canvas.parentnode, styles = getcomputedstyle(parent), w = parseint(styles.getpropertyvalue("width"), 10), h = parseint(styles.getpropertyvalue("height"), 10); canvas.width = w; canvas.height = h;
(note: chrome seem have issues computed flex @ moment)
update
here's simpler way:
var rect = canvas.parentnode.getboundingclientrect(); canvas.width = rect.width; canvas.height = rect.height;
Comments
Post a Comment