It is important to ensure that your code executes after the DOM has finished loading. Attempting to append elements to the body before it exists can cause errors.
To address this issue, you should enclose your code in a block that will be executed once the DOM is ready or when the entire window's content has been fully loaded:
See an Example Here
window.addEventListener("load", function () {
var body, canvas, img, ctx;
body = document.getElementsByTagName("body")[0];
canvas = document.createElement("canvas");
canvas.style.width = "500px";
canvas.style.height = "400px";
body.appendChild(canvas);
img = document.createElement("img");
ctx = canvas.getContext("2d");
img.onload = function () {
ctx.drawImage(img, 0, 0, 500, 400, 0, 0, 350, 200);
}
img.src = "http://cdn.sstatic.net/stackoverflow/img/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="35544545595018415a40565d185c565a5b75">[email protected]</a>?v=fde6657a82e6";
});