0

I've created a game that works with canvas, and i need it to be in a very low resolution to fit a software I'm working with. besically when I draw a diagonal line it should appear as a diagonal row of squares.

I did

context.mozImageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;      

but it's just blurry. How can I convert it?

i have the top one, i want the bottom

the top picture is what it looks like now and the bottom is what i want it to look like

Dotan
  • 6,602
  • 10
  • 34
  • 47
  • [Possible duplicate](http://stackoverflow.com/questions/19129644/how-to-pixelate-an-image-with-canvas-and-javascript) – chead23 Dec 01 '14 at 08:46
  • I saw it, they are talking about pixalating images - this is not an image, although I'd be happy for ideas on how to convert it into an image and then pixalating it – Dotan Dec 01 '14 at 08:58

1 Answers1

1

One approach is to use image smoothing disabled with a low-resolution canvas. Though you will get a blocky line, you will also get the anti-aliased pixels included. The only way to avoid this is to implement line algorithms etc. yourselves such as Bresenham (see below example).

You can also draw the lines, then run through the bitmap pixel by pixel and use a threshold value to filter the anti-aliased pixels away but this will give various results and is dependent on having isolated paths to work with, ie. draw to off-screen, filter with threshold, then draw result to main canvas.

An example:

var mctx = main.getContext("2d"),
    lowRes = document.createElement("canvas"),
    ctx = lowRes.getContext("2d");

// setup low-res canvas (invisible)
lowRes.width = 32;
lowRes.height = 20;

// setup main visible canvas
mctx.imageSmoothingEnabled =
mctx.msImageSmoothingEnabled =
mctx.mozImageSmoothingEnabled =
mctx.webkitImageSmoothingEnabled = false;

// draw a line to off-screen canvas
ctx.moveTo(0, lowRes.height);
ctx.lineTo(lowRes.width - 7, 4);
ctx.lineWidth=4;
ctx.strokeStyle = "#fff";
ctx.stroke();

// draw bacground on main canvas
mctx.fillRect(0,0,500,300);

// draw in low-res line
mctx.drawImage(lowRes, 0,0,lowRes.width,lowRes.height,
                       0,0,main.width,main.height);
<canvas id="main" width=500 height=300></canvas>

I would also like to propose to check out my Retro Context library (free/GPL3) which was made for this very reason. It has implemented all these line algorithms and has a full and simple API to access them (and much more "retro" related).

Optionally, you would need to implement these line algorithms yourselves. Here are some resources to help you get started if you chose this approach:

  • 1
    @Dotan Reis I would endorse using Ken's Retro Context Library. It's solid and just plain cool! – markE Dec 01 '14 at 17:01