0

I'm new to javascript and web development in general, and I'm trying to write a renderer that can draw each slice in a CT scan as a 2D image.

I have a long thin (512x49664) image made from 512x97 slices, each of which is just a 512x512 image. I've already ascertained that this will upset webgl, so I was planning to grab individual slices from the image by drawing it on a canvas and copying the image data into a texture.

My question is: if I have a function in which I do something like:

// Create a small canvas to contain a single slice.
function getSlice(sliceNumber){
    var sliceCanvas = document.createElement("canvas");
    sliceCanvas.width = 512;
    sliceCanvas.height = 512;
    var sliceContext = sliceCanvas.getContext('2d');
    sliceContext.drawImage(image, 0, 512*sliceNumber, 512, 512, 0, 0, 512, 512);
}

What happens to the canvas I created when the function exits?

3
  • you create your canvas element in getSlice(). so it will not be available/disposed after the function got executed. Commented Aug 2, 2016 at 9:10
  • This article covers memory mangement quite well Commented Aug 2, 2016 at 9:13
  • FYI you've created an element but you've not put it in the DOM so it will not be rendered Commented Aug 2, 2016 at 9:15

2 Answers 2

1

It hasn't been:

  • Added to the DOM
  • Stored in a variable or property that is still in scope
  • Returned anywhere

… there are no references remaining to it, so it will be marked for garbage collection.

Sign up to request clarification or add additional context in comments.

Comments

1

When you create a DOM element via javascript DOM API, you should attach this element to the page document.

Otherwise this element will never shown in your page.

So you have to add a line like this in your code:

document.body.appendChild(sliceCanvas);

If you call your function multiple times, you should check the canvas creation:

var sliceCanvas = document.getElementsByTagName('canvas')[0];

or

var sliceCanvas = document.getElementById('myCanvasId');

Then check:

if (!sliceCanvas) {
    sliceCanvas = document.createElement('canvas');
    sliceCanvas.id = 'myCanvasId'; // optional
    document.body.appendChild(sliceCanvas);
}

// here your code...

UPDATE:

Consider to change the document.body with the proper DOM element where you want to place your canvas.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.