Search code examples
javascriptjqueryhtmldicom

How to change window center and width of an image on mouse move event


I have a DICOM image and i want to apply a W/L on the image. In normal terms, i am trying to change the color of the image as i drag the mouse over it. however it becomes completely white when i try to change it.

here's what I am doing.

this is just a part of the code.

var imageData = ctx.getImageData(0, 0, img.width, img.height);
var data = imageData.data;

var pixels = imageData.data,
    len = pixels.length;
var a = 256 * slope / window_width,
    b = 256 * ((intercept - window_level) / window_width);

for (i = 0; i < len; i += 4) {
    //pixval = a * (pixels[i] * 256 + pixels[i + 1]) + b;
    //pixels[i] = pixels[i + 1] = pixels[i + 2] = pixval

    if (pixels[i + 3] == 0)
        continue;

    var pixelIndex = i;
    var red = pixels[pixelIndex]; // red   color
    var green = pixels[pixelIndex + 1]; // green color
    var blue = pixels[pixelIndex + 2]; // blue  color
    var alpha = pixels[pixelIndex + 3];

    var pixelValue = a * (red * 256 + green + b);
    pixels[i] = pixels[i + 1] = pixels[i + 2] = pixelValue;
    pixels[i + 3] = 0xff;
    //console.log(pixelValue == pixval);

}

here's the JSFIDDLE with the complete code.


Solution

  • The main problem is that you're changing your image data when drawing it. You need to store a raw version of your image data, then "apply" your window level dynamically when drawing. Otherwise, you're just compounding the changes on top of each other.

    Try making two canvas objects: one (offscreen) to load and store your image data and the other to draw it. Making this relatively small change to your code, it appeared to work right.

    There may be other issues with your starting values -- I think you may be missing rescale slope and intercept -- but fixing the first issue should make everything easier to figure out.

    Here's the jsfiddle: https://jsfiddle.net/8ne1pnaj/5/

    var imageData = ctxData.getImageData(0, 0, img.width, img.height);
    // ...
    ctx.putImageData(imageData, 0, 0)
    

    ctxData is the original data. ctx is the drawing context.