HTML5 Canvas - how to enlarge image?

How can I enlarge the canvas to see the pixels? Currently, when I try to use the scale () function, the image is always smoothed.

The property mozImageSmoothingEnabledseems to work, but it is only for Firefox.

+3
source share
2 answers

As far as I know, any scaling performed by the browser will result in smooth interpolation.

So, if you want to do this with JS, you have to let JS do all the work. This means either finding a good library, or writing a function yourself. It might look like this. But I hope this can be done faster. Since this is one of the simplest scaling algorithms, there are probably many people who have come up with improvements to make this even faster.

function resize(ctx, sx, sy, sw, sh, tx, ty, tw, th) {
    var source = ctx.getImageData(sx, sy, sw, sh);
    var sdata = source.data;

    var target = ctx.createImageData(tw, th);
    var tdata = target.data;

    var mapx = [];
    var ratiox = sw / tw, px = 0;
    for (var i = 0; i < tw; ++i) {
        mapx[i] = 4 * Math.floor(px);
        px += ratiox;
    }

    var mapy = [];
    var ratioy = sh / th, py = 0;
    for (var i = 0; i < th; ++i) {
        mapy[i] = 4 * sw * Math.floor(py);
        py += ratioy;
    }

    var tp = 0;
    for (py = 0; py < th; ++py) {
        for (px = 0; px < tw; ++px) {
            var sp = mapx[px] + mapy[py];
            tdata[tp++] = sdata[sp++];
            tdata[tp++] = sdata[sp++];
            tdata[tp++] = sdata[sp++];
            tdata[tp++] = sdata[sp++];
        }
    }

    ctx.putImageData(target, tx, ty);
}

This function will take a rectangle of size (sw, sh) in (sx, sy), resize it to (tw, th) and draw on (tx, ty).

+3
source

As far as I know, the smoothing behavior is not defined in the specification and will depend on the browser.

, , - / CSS 300x300, 150 150, "" 200%. , , .

0

Source: https://habr.com/ru/post/1779840/


All Articles