javascript - replacing old canvas with new one with scaled image -
i have canvas loaded image on top of it. canvas has static widkth , height (800x600). image can smaller or larger. if image smaller size of canvas, placed on middle using following code
x = (canvas.width - image.width)/2; y = (canvas.height - image.height) / 2; ctx.drawimage(image, x, y)
i want replace old canvas new 1 has image scaled accoring ratio. code following(for testing purposes render image on top left corner of canvas, not yet implemented exact position)
oldcanvas = document.getelementbyid('mycanvas'); newcanvas = document.createelement('canvas'); ctx = newcanvas.getcontext('2d'); x = y = 0; newimagewidth = image.width * 2; newimageheight = image.height * 2; ctx.drawimage(oldcanvas, x, y, newimagewidth, newimageheight); oldcanvas.parentnode.replacechild(newcanvas, oldcanvas)
but canvas stays same old. tried doing same witout scaling image changing size of newcanvas , worked.what doing wrong in here?
edit: works if chnage drawimage original image parameter
ctx.drawimage(image, 0, 0, newimagewidth, newimageheight);
but want use old canvas because image migth edited e.g changed brightness. isn't same use canvas element instead of image element on canvas?
edit2: in order comply stack's overflow policy, asking here: there difference between calling drawimage image parameter , canvas parameter?
yes, can use either image element or existing canvas image source drawimage.
your glitch you're using version of drawimage clips, not scales:
// clips newimagewidth x newimageheight pixels oldcanvas @ x,y ctx.drawimage(oldcanvas, x, y, newimagewidth, newimageheight);
instead, use scaling version of drawimage:
ctx.drawimage(oldcanvas, // use old canvas image source 0,0, oldcanvas.width,oldcanvas.height, // use entire old canvas x,y, newimagewidth, newimageheight); // scale old canvas new size
Comments
Post a Comment