how to set the width and heigth of the canvas to be the same size as that of an image

JavaScript
<canvas id="canvas"><img src="dynamic_url" id="dynamic_img" /></canvas>
function resizeCanvas()
{
    var img = document.getElementById('dynamic_img'); 
    var width = img.clientWidth;
    var height = img.clientHeight;

    var canvas = document.getElementById('canvas'); 
    canvas.style.width = width;
    canvas.style.height = height;
}

Source

Also in JavaScript: