Draw out of canvas JavaScript - javascript

I have been developing a program which includes some sort of genetic algorithm. For my program, let's say there is a population of 200 units, and each unit can be in 5 different states. Inititlly, they all start at state 0, and they can randomly jump to states 1 to 4, and influence other units to jump as well. This way, the more units are on state 2, the more units will jump to state 2 and so on. I have these units moving randomly inside my canvas, bouncing off the walls when they hit them.
The one thing I want to do now is visualize the evolution on a chart, and for that I would like to have the canvas with the units jumping states on one side and the chart next to it, dynamically representing the percentage of units in state 0, 1, 2... simultaneously. I will presumably have no problem in coding the chart, however I cannot find a way of displaying it outside the canvas or without altering it.
Just in case, I am programming in Atom and have mostly used p5 libraries.
Any ideas??

You have 2 options:
Make a second canvas (Like enhzflep said), but this might be complicated for you, becuase you will not have access to P5.js drawing tools on that second canvas, look at this:
(On your first canvas)
fill(255,0,0)
rect(50,50,50,50);
To make and draw to a second canvas:
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
//deal with positioning, scaling, and other stuff (comment if you need help with that)
...
const c = canvas.getContext('2d');
c.fillStyle = "rgb(255,0,0)";
c.fillRect(50,50,50,50);
(See, lots of effort)
Or, you can just use your first canvas, and partition a section off that is dedicated to the graph
createCanvas(600 + graphWidth, 600);
//Wherever your bouncing off walls code is
//for the right side of the screen
if(this.x > width - graphWidth){
bounce();
}
//that leaves you a graphWidth by 600 rectangle for you to draw you graph
The second option is much easier to read and will save you some headaches (I would use that).

Related

Pixelated Lines (HTML Canvas) [duplicate]

I have been writing a little javascript plugin, and i am having a little trouble with improving the canvas overall quality of the render. I have searched over the web here and there but can not find anything that makes sense.
The lines created from my curves are NOT smooth, if you look at the jsfiddle below you will understand what I mean. It kind of looks pixelated. Is there a way to improve the quality? Or is there a Canvas Framework that already uses some method to auto improve its quality that I can use in my project?
My Canvas Render
Not sure if this helps but i am using this code at the start of my script:
var c = document.getElementsByClassName("canvas");
for (i = 0; i < c.length; i++) {
var canvas = c[i];
var ctx = canvas.getContext("2d");
ctx.clearRect(0,0, canvas.width, canvas.height);
ctx.lineWidth=1;
}
}
Thanks in advance
Example of my Curve Code:
var data = {
diameter: 250,
slant: 20,
height: 290
};
for (i = 0; i < c.length; i++) {
var canvas = c[i];
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo( 150 + ((data.diameter / 2) + data.slant ), (data.height - 3) );
ctx.quadraticCurveTo( 150 , (data.height - 15), 150 - ((data.diameter / 2) + data.slant ), (data.height - 3));
ctx.lineTo( 150 - ((data.diameter / 2) + data.slant ), data.height );
ctx.quadraticCurveTo( 150 , (data.height + 5), 150 + ((data.diameter / 2) + data.slant ), data.height);
ctx.closePath();
ctx.stroke();
}
The Problem
This is one of those cases where it's almost impossible to get a smooth result without manually tweaking it.
The cause has to do with the minimal space to distribute smoothing pixels. In this case we only have a single pixel height between each section in the quadratic curve.
If we look at a curve with no smoothing we can more clearly see this limitation (without smoothing each pixel sits on an integer position):
The red line indicates a single section and we can see that the transition between the previous and next section has to be distributed over the height one pixel. See my answer here for how this works.
Smoothing is based on the remaining fraction for the point's coordinate conversion to integer. Since smoothing then uses this fraction to determine the color and alpha based on stroke main color and background color to add a shaded pixel, we will quickly run into limitations as each pixel used for smoothing occupies a whole pixel itself and due to the lack of space as here, the shades will be very rough and therefor revealing.
When a long line goes from y to y+/-1 (or x to x+/-1) there is not a single pixel between the end points that would land on a perfect bound which means every pixel between is instead a shade.
If we take a closer look at a couple of segments from the current line we can see the shades more clearly and how it affects the result :
Additionally
Though this explains the principle in general - Other problems are (as I barely hinted about in revision 1 (last paragraph) of this answer a few days ago, but removed and forgot about going deeper into it) is that lines drawn on top of each other in general, will contribute to contrast as the alpha pixels will blend and in some parts introduce higher contrast.
You will have to go over the code to remove unneeded strokes so you get a single stroke in each location. You have for instance some closePaths() that will connect end of path with the beginning and draw double lines and so forth.
A combination of these two should give a nice balance between smooth and sharp.
Smoothing test-bench
This demo allows you to see the effect for how smoothing is distributed based on available space.
The more bent the curve is, the shorter each section becomes and would require less smoothing. The result: smoother line.
var ctx = c.getContext("2d");
ctx.imageSmoothingEnabled =
ctx.mozImageSmoothingEnabled = ctx.webkitImageSmoothingEnabled = false; // for zoom!
function render() {
ctx.clearRect(0, 0, c.width, c.height);
!!t.checked ? ctx.setTransform(1,0,0,1,0.5,0.5):ctx.setTransform(1,0,0,1,0,0);
ctx.beginPath();
ctx.moveTo(0,1);
ctx.quadraticCurveTo(150, +v.value, 300, 1);
ctx.lineWidth = +lw.value;
ctx.strokeStyle = "hsl(0,0%," + l.value + "%)";
ctx.stroke();
vv.innerHTML = v.value;
lv.innerHTML = l.value;
lwv.innerHTML = lw.value;
ctx.drawImage(c, 0, 0, 300, 300, 304, 0, 1200, 1200); // zoom
}
render();
v.oninput=v.onchange=l.oninput=l.onchange=t.onchange=lw.oninput=render;
html, body {margin:0;font:12px sans-serif}; #c {margin-top:5px}
<label>Bend: <input id=v type=range min=1 max=290 value=1></label>
<span id=vv></span><br>
<label>Lightness: <input id=l type=range min=0 max=60 value=0></label>
<span id=lv></span><br>
<label>Translate 1/2 pixel: <input id=t type=checkbox></label><br>
<label>Line width: <input id=lw type=range min=0.25 max=2 step=0.25 value=1></label>
<span id=lwv></span><br>
<canvas id=c width=580></canvas>
Solution
There is no good solution unless the resolution could have been increased. So we are stuck with tweaking the colors and geometry to give a more smooth result.
We can use a few of tricks to get around:
We can reduce the line width to 0.5 - 0.75 so we get a less visible color gradient used for shading.
We can dim the color to decrease the contrast
We can translate half pixel. This will work in some cases, others not.
If sharpness is not essential, increasing the line width instead may help balancing out shades. Example value could be 1.5 combined with a lighter color/gray.
We could use shadow too but this is an performance hungry approach as it uses more memory as well as Gaussian blur, together with two extra composition steps and is relatively slow. I would recommend using 4) instead.
1) and 2) are somewhat related as using a line width < 1 will force sub-pixeling on the whole line which means no pixel is pure black. The goal of both techniques is to reduce the contrast to camouflage the shade gradients giving the illusion of being a sharper/thinner line.
Note that 3) will only improve pixels that as a result lands on a exact pixel bound. All other cases will still be blurry. In this case this trick will have little to no effect on the curve, but serves well for the rectangles and vertical and horizontal lines.
If we apply these tricks by using the test-bench above, we'll get some usable values:
Variation 1
ctx.lineWidth = 1.25; // gives some space for lightness
ctx.strokeStyle = "hsl(0,0%,50%)"; // reduces contrast
ctx.setTransform(1,0,0,1,0.5,0.5); // not so useful for the curve itself
Variation 2:
ctx.lineWidth = 0.5; // sub-pixels all points
ctx.setTransform(1,0,0,1,0.5,0.5); // not so useful for the curve itself
We can fine-tune further by experimenting with line width and the stroke color/lightness.
An alternative is to produce a more accurate result for the curves using Photoshop or something similar which has better smoothing algorithms, and use that as image instead of using native curve.
This question struck me as a little odd. Canvas rendering, though not the best when compared to high end renderers is still very good. So why is there such a problem with this example. I was about to leave it, but 500 points is worth another look. From that I can give two bits of advice, a solution, and an alternative.
First, designers and their designs must incorporate the limits of the media. It may sound a little presumptuous but you are trying to reduce the irreducible, you can not get rid of aliasing on a bitmap display.
Second, Always write neat well commented code. There are 4 answers here and no-one picked out the flaw. That is because the presented code is rather messy and hard to understand. I am guessing (almost like me) the others skipped your code altogether rather than work out what it was doing wrong.
Please Note
The quality of images in all the answers for this question may be scaled (thus resampled) by the browser. To make a true comparison it is best to view the images on a separate page so that they are not scaled.
Results of study of problem in order of quality (in my view)
Genetic algorithm
The best method I found to improve the quality, a method not normally associated to computer graphics, is to use a very simple form of a genetic algorithm (GA) to search for the best solution by making subtle changes to the rendering process.
Sub pixel positioning, line width, filter selection, compositing, resampling and colour changes can make marked changes to the final result. This present billions of possible combinations, any one of which could be the best. GAs are well suited to finding solutions to these types of searches, though in this case the fitness test was problematic, because the quality is subjective the fitness test has to be also, and thus requires human input.
After many iterations and taking up rather a bit more of my time than I wanted I found a method very well suited to this type of image (many thin closely spaced lines) The GA is not suitable for public release. Fortunately we are only interested in the fittest solution and the GA created a sequence of steps that are repeatable and consistent for the particular style it was run to solve.
The result of the GA search is.
see Note 1 for processing steps
The results is far better than I expected so I had to have a closed look and noticed 2 distinct features that set this image apart from all the others presented in this and other answers.
Anti-aliasing is non uniform. Where you would normally expect a uniform change in intensity this method produces a stepped gradient (why this makes it look better I do not know)
Dark nodes. Just where the transition from one row to the next is almost complete the line below or above is rendered noticeably darker for a few pixels then reverts back to the lighter shade when the line is fitting the row. This seams to compensate lightening of the overall line as it shares its intencity across two rows.
This has given me some food for thought and I will see if these features can be incorporated directly into the line and curve scan line rendering.
Note 1
The methods used to render the above image. Off screen canvas size 1200 by 1200. Rendered at scale 4 ctx.setTransform(4,0,0,4,0,0), pixel y offset 3 ctx.translate(0,3), Line width 0.9pixels rendered twice on white background, 1 pixel photon count blur repeated 3 times (similar to convolution 3*3 gaussian blur but a little less weight along the diagonals), 4 times down samples via 2 step downsample using photon count means (each pixel channel is the square root of the mean of the squares of the 4 (2 by 2) sampled pixels). Sharpen one pass (unfortunately that is a very complex custom sharpen filter (like some pin/pixel sharpen filters)) and then layered once with ctx.globalCompositeOperation = "multiply" and ctx.globalAlpha = 0.433 then captured on canvas. All processing done on Firefox
Code fix
The awful rendering result was actually caused by some minor rendering inconsistencies in you code.
Below is the before and after the code fix. As you can see there is a marked improvement.
So what did you do wrong?
Not to much, the problem is that you where rendering lines over the top of existing lines. This has the effect of increasing the contrast of those lines, the render does not know you don't want the existing colours and thus adds to the existing anti aliasing doubling the opacity and destroying the effect.
Bellow your code with only the rendering of the shape. Comments show the changes.
ctx.beginPath();
// removed the top and bottom lines of the rectangle
ctx.moveTo(150, 0);
ctx.lineTo(150, 75);
ctx.moveTo(153, 0);
ctx.lineTo(153, 75);
// dont need close path
ctx.stroke();
ctx.beginPath();
ctx.moveTo((150 - (data.diameter / 2)), 80);
ctx.quadraticCurveTo(150, 70, 150 + (data.diameter / 2), 80);
ctx.lineTo(150 + (data.diameter / 2), 83);
ctx.quadraticCurveTo(150, 73, 150 - (data.diameter / 2), 83);
ctx.closePath();
ctx.stroke();
ctx.beginPath();
// removed the two quadratic curves that where drawing over the top of existing ones
ctx.moveTo(150 + (data.diameter / 2), 83);
ctx.lineTo(150 + ((data.diameter / 2) + data.slant), data.height);
ctx.moveTo(150 - ((data.diameter / 2) + data.slant), data.height);
ctx.lineTo(150 - (data.diameter / 2), 83);
// dont need close path
ctx.stroke();
ctx.beginPath();
// removed a curve
ctx.moveTo(150 + ((data.diameter / 2) + data.slant), (data.height - 3));
ctx.quadraticCurveTo(150, (data.height - 15), 150 - ((data.diameter / 2) + data.slant), (data.height - 3));
// dont need close path
ctx.stroke();
ctx.beginPath();
ctx.moveTo(150 + ((data.diameter / 2) + data.slant), data.height);
ctx.quadraticCurveTo(150, (data.height - 10), 150 - ((data.diameter / 2) + data.slant), data.height);
ctx.quadraticCurveTo(150, (data.height + 5), 150 + ((data.diameter / 2) + data.slant), data.height);
ctx.closePath();
ctx.stroke();
So now the render is much better.
Subjective eye
The code fix in my opinion is the best solution that can be achieved with the minimum of effort. As quality is subjective below I present several more methods that may or may not improve the quality, dependent on the eye of the judge.
DOWN SAMPLING
Another why of improving render quality is to down sample.This involves simply rendering the image at a higher resolution and then re rendering the image at a lower resolution. Each pixel is then an average of 2 or more pixels from the original.
There are many down sampling methods, but many are not of any practical use due to the time they take to process the image.
The quickest down sampling can be done via the GPU and native canvas render calls. Simply create an offscreen canvas at a resolution 2 time or 4 time greater than required, then use the transform to scale the image rendering up (so you don't need to change the rendering code). Then you render that image at the required resolution for the result.
Example of downsampling using 2D API and JS
var canvas = document.getElementById("myCanvas"); // get onscreen canvas
// set up the up scales offscreen canvas
var display = {};
display.width = canvas.width;
display.height = canvas.height;
var downSampleSize = 2;
var canvasUp = document.createElement("canvas");
canvasUp.width = display.width * downSampleSize;
canvasUp.height = display.height * downSampleSize;
var ctx = canvasUp.getContext("2D");
ctx.setTransform(downSampleSize,0,0,downSampleSize,0,0);
// call the render function and render to the offscreen canvas
Once you have the image just render it to you onscreen canvas
ctx = canvas.getContext("2d");
ctx.drawImage(canvasUp,0,0,canvas.width,canvas.height);
The following images shows the result of 4* down sampling and varying the line width from 1.2 pixels down to 0.9 pixels (Note the upsampled line width is 4 * that. 4.8, 4.4, 4, & 3.6)
Next image 4* down sample using Lanczos resampling a reasonably quick resample (better suited to pictures)
Down sampling is quick and requires very little modification to the original code to work. The resulting image will improve the look of fine detail and create a slightly better antialiased line.
Down sampling also allows for much finer control of the (apparent) line width. rendering at display resolution gives poor results under 1/4 pixel changes in line width. Using downsampling you double and quadruple that 1/8th and 1/16th fine detail (keep in mind there are other types of aliasing effect that come into play when rendering at sub pixels resolutions)
Dynamic Range
Dynamic range in digital media refers to the range of values that the media can handle. For the canvas that range is 256 (8bits) per color channel. The human eye has a hard time picking the difference between to concurrent values, say 128 and 129 so this range is almost ubiquitous in the realm of computer graphics. Modern GPU though can render at much higher dynamic ranges 16bit, 24bit, 32bit per channel and even double precision floats 64bit.
The adequate 8bit range is good for 95% of cases but suffers when the image being rendered is forced into a lower dynamic range. This happens when you render a line on top of a colour that is close to the line colour. In the questio the image is rendered on not a very bright background (example #888), the result is that the anti aliasing only has a range of 7 bits halving the dynamic range. The problem is compounded by the fact that if the image is rendered onto a transparent background where the anti aliasing is achieved by varying the alpha channel, resulting in the introduction of a second level of artifacts.
When you keep dynamic range in mind you can design your imagery to get the best result (within the design constraints). When rendering and the background is known, don't render onto a transparent canvas letting the hardware composite the final screen output, render the background onto the canvas, then render the design. Try to keep the dynamic range as large as possible, the greater the difference in colour the better the antialiasing algorithm can deal with the intermediate colour.
Below is an example of rendering to various background intensities, they are rendered using 2* down sampling on pre rendered background. BG denotes the background intensity .
Please note that this image is to wide too fit the page and is down sampled by the browser thus adding extra artifacts.
TRUE TYPE like
While here there is another method. If you consider the screen made up of pixels, each pixel has 3 parts red, green, blue and we group them always starting at red.
But it does not matter where a pixels starts, all that matters is that the pixel has the 3 colours rgb, it could be gbr or brg. When you look at the screen like this you effectively get 3 times the horizontal resolution in regard to the edges of the pixels. The pixel size is still the same but offset. This is how microsoft does its special font rendering (true type) Unfortunately Microsoft have many patents on the use of this method so all I can do is show you what it looks like when you render ignoring pixel boundaries.
The effect is most pronounced in the horizontal resolution, and does not improve the vertical much (Note this is my own implementation of the canvas rendering and it's still being refined) This method also does not work for transparent images
What is a slanted line on a pixel matrix is what you should understand. If you need to draw a slanted line of a single pixel width, there is no way you can prevent it from having jagged edges on it since slanting is achieved via a progressing vertical pattern of horizontal lines.
The solution is to have some blur effect around the lines and make the line joining smoother.
You need to use shadowColor, shadowBlur, lineCap and lineJoin properties of the canvas context to achieve this.
Put the following setup and try drawing you lines.
for (i = 0; i < c.length; i++) {
var canvas = c[i];
var ctx = canvas.getContext("2d");
ctx.shadowColor = "rgba(0,0,0,1)";
ctx.shadowBlur = 2;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.lineWidth = 1;
ctx.strokeStyle = 'black';
ctx.clearRect(0,0, canvas.width, canvas.height);
}
Here is the result
Try playing with the shadowColor opacity and the blur size together with the line width and color. You can get pretty amazing results.
On a side note, your project sounds more SVG to me than Canvas. Probably you should think of moving to SVG to get better drawing support and performance.
Update
Here is a fine adjustment
ctx.shadowColor = "rgba(128,128,128,.2)";
ctx.shadowBlur = 1;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.lineWidth = 1;
ctx.strokeStyle = 'gray';
Sorry I'm late to the party, but all of the answers here are overcomplicating things.
What you are actually seeing is the absence of gamma correction. Look at the Antialias 1&2 examples here: http://bourt.com/2014/ (you'll need to calibrate the gamma value for your monitor first), and this short explanation: https://medium.com/#alexbourt/use-gamma-everywhere-da027d9dc82f
The vectors are drawn as if in a linear color space, while the pixels exist in a gamma-corrected space. It's that simple. Unfortunately, Canvas has no gamma support, so you're kind of stuck.
There is a way to fix this, but you have to draw your stuff, then access the pixels directly and correct them for gamma yourself, like I did in those examples. Naturally, this is most easily done with simple graphics. For anything more complicated you need your own rendering pipeline which takes gamma into account.
(Because this argument invariably comes up, I'll address it now: it's better to err on the side of gamma than not. If you say "well, I don't know what the user monitor's gamma will be", and leave it at 1.0, the result WILL BE WRONG in almost all cases. But if you take an educated guess, say 1.8, then for a substantial percentage of users you will have guessed something close to what's correct for their monitor.)
One reason for blury lines is drawing in-between pixels. This answer gives a good overview of the canvas coordinate system:
https://stackoverflow.com/a/3657831/4602079
One way of keeping integer coordinates but still getting crisp lines is to translate the context by 0.5 pixel:
context.translate(0.5,0.5);
Take a look at the snippet below. The second canvas is translated by (0.5, 0.5) making the line drawn with integer coordinates look crisp.
That should get your straight lines fixed. Curves, diagonal lines, etc. will be anti-aliased (gray pixels around the strokes). Not much you can do about it. The higher the resolution less visible they are and all lines except for the straight ones look better anti-aliased anyways.
function draw(ctx){
ctx.beginPath();
ctx.moveTo(25, 30);
ctx.lineTo(75, 30);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(25, 50.5);
ctx.lineTo(75, 50.5);
ctx.stroke();
}
draw(document.getElementById("c1").getContext("2d"))
var ctx = document.getElementById("c2").getContext("2d");
ctx.translate(0.5, 0.5);
draw(ctx);
<canvas id="c1" width="100" height="100" style="width: 100px; height: 100px"></canvas>
<canvas id="c2" width="100" height="100" style="width: 100px; height: 100px"></canvas>
Anti-aliasing helps a lot. But when you have angled lines that are close to horizontal, or vertical, or are gently curving, the anti-aliasing is going to be a lot more noticeable. Especially for thin lines with widths of less than a couple of a pixels or so.
As Maciej points out, if you have a line that's around 1px width and it passed directly between two pixels, anti-aliasing will result in a line that's two pixels wide and half-grey.
You may have to just learn to live with it. There is only so much that anti-aliasing can do.

HTML5 canvas - How to clear and redraw regions with overlapping entities?

Up until now, I've been clearing/redrawing everything on a single canvas at each animation frame, which is naturally very expensive. I've been leaning towards the idea of using multiple canvases, each representing a different layer in the game, and only redrawing regions of the canvas that have changed. This has the potential to drastically reduce the amount of clearing and redrawing in the game (and subsequently improve performance), however I'm foreseeing a problem to this.
Splitting the game components into layers is fine, however if there is a layer with a group of entities that move around, there will be times when one mobile entity overlaps an immobile one. As the immobile one hasn't changed, it is not scheduled for a redraw. The part of the immobile entity's image that was cleared by the mobile entity's movement then never gets redrawn (see below images).
Black stationary background layer + Foreground layer with moving entities. The white entity is moving, but the yellow one isn't.
As the yellow entity isn't moving, it is generally safe to say that the pixels in its region have not changed. However the white entity's movement causes some of those pixels to be cleared.
Here are the solutions I have come up with:
1) Like before, clear and redraw the entire canvas, but only for the layer with moving entities. In my game 1 of 4 layers fits into this category.
2) Calculate when objects overlap, and clear/redraw both regions in these situations.
3) Move the stationary entities temporarily to a background layer and process as normal.
Comments for each solution:
1) This solution feels like it will not have enough of a performance gain to warrant the redesign.
2) This feels like a more efficient approach, but still requires testing among all entities to see if their borders collide. If the number of entities is great enough, this would have to be further improved by splitting the canvas into regions and processing each region individually.
3) This approach gives me the desirable result of drawing moving entities over stationary ones, but is it as efficient as solution 2?
Are there any other potentially better solutions?
As requested by Blindman67, here is my draw code:
Sprite.prototype.draw = function()
{
if (this.hasImage())
{
if (this.opacity == 1)
{
this.drawImage()
}
else
{
game.ctx.globalAlpha = this.opacity;
this.drawWithTransparency();
game.ctx.globalAlpha = 1;
}
}
}
Sprite.prototype.drawImage = function()
{
game.ctx.drawImage(
this.image,
this.position.x,
this.position.y,
this.image.width,
this.image.height
);
}
I clear the canvas once at the beginning of every update.

JavaScript canvas clearRect leaves borders when using floating point coordinates

I am using clearRect on a HTML5 canvas to redraw a rectangle. When using floating point coordinates the clearRect leaves a border from my rectangle on the canvas.
The following code demonstrates the problem with the rectangle using integer coordinates being fully cleared while the one using floating point leaves a border.
<html>
<head>
</head>
<body>
<script type="text/javascript" >
var canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
canvas.style.border = "1px solid";
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");
ctx.fillRect(20.1,20.1,30,30);
ctx.clearRect(20.1,20.1,30,30);
ctx.fillRect(50,50,30,30);
ctx.clearRect(50,50,30,30);
</script>
</body>
</html>
The resulting canvas looks like this:
I can fix this by clearing a larger region, but that increases the risk of clearing and having to redraw adjacent shapes. This is for example suggested here: I can't completely clear the transformed rectangle in <canvas>
I can fix it by using integer coordinates, but that is not an option in this application.
Are there other ways to make clearRect actually clear all of the drawn rectangle without clearing a larger region or using integer coordinates?
All points in canvas are in fact centered in their middle coordinates (0.5, 0.5).
If you want to draw a black line one pixel thick, you'll have to draw it with centered coordinates.
If you draw it on an integer boundary, you'll in fact draw a two pixel thick lines both with lower opacity, leading to a thicker line drawn in dark gray instead of black :
Here's a picture showing this, zoomed 3 times :
More generally, any coordinates off the 0.5 boundary will be drawn with an opacity proportional to its distance to mid point.
Here's a set of horizontal line segments starting on an integer boundary, then shifted 1/10th of a pixel every 20 pixels :
zoomed 4 times :
We can see that we really have a 1 pixel line only when centered.
For your issue, there's no way you 'partially' clear a pixel : pixel is the ultimate unit here, so since colors have already been mixed, you can only either clear whole pixel, or just attenuate its intensity (which is the result you see).
I can think of two solutions :
rather than clearing, redraw everything except what you don't want any more. For this you have to handle some kind of scene graph, meaning : you need to have a collection of all the objects that needs drawing (held within an array for instance), and at draw time, you erase everything, redraw everything except the rectangle.
handle a bigger canvas behind the scene, that will have a higher resolution than the user canvas. This is were you draw, with better quality, and after drawing you copy it to the low-resolution user canvas.
Draw on 0.5 boundaries with integer sizes (width/height of your rect for instance). This main canvas might be 4 or 8 times bigger. The maximum size of the canvas is limited, so watch out for this if you target all browsers, they do not all allow the same max size (below 6400X6400 should be fine, but not sure about it). You can handle multiples backstage canvas to go beyond that limit, with a little bit of extra work.
(Rq for solution 2 : be sure to disable image smoothing before copying to avoid artifacts).
(( the fiddle for the drawings is here : jsbin.com/xucuxoxo/1/ ))
Edit : it is a good practice to translate the context from (0.5;0.5) right after you created it. Then you will always draw integer coordinates. This way, you ensure that all, say, 1 pixel thick line will actually be drawn one pixel thick. Test rounding with floor or ceil, and choose the one you prefer.
Html canvas always applies anti-aliasing to "cure the jaggies".
Anti-aliasing visually smooths lines by adding semi-transparent pixels along the line so the eye is fooled into seeing a less-jagged line.
When you draw your rectangles, these semi-transparent pixels are automatically being applied outside the 30,30 area of your rectangles.
This means your 30x30 rectangle is actually slightly larger than 30x30.
When you do context.clearRect the browser does not clear those extra semi-transparent pixels.
That's why the uncleared pixels appear "ghostly" -- they are semi-transparent.
Unfortunately, there is no way currently to turn off anti-aliasing for html canvas primitive drawing (lines, etc).
You have discovered the 2 fastest solutions:
round pixel drawing coordinates to integers
clear an area slightly larger than the original drawing
You can draw without anti-aliasing by drawing pixels manually using getImageData/putImageData. This manual method works but is costly to performance. The decreased performance defeats the purpose of clearing just the drawn area.
Bottom line: You've already discovered the best solutions canvas currently has to offer :-(

Parallax effect with zoom and rotating

I am currently experimenting with parallax effect that i am planning to implement to my HTML5-canvas game engine.
The effect itself is fairly easy to achieve, but when you add zooming and rotating, things get a little more complicated, at least for me. My goal is to achieve something like this:Youtube video.
As you can see, you can zoom in and out "to the center", and also rotate around it and get the parallax effect.
In my engine i want to have multiple canvases that are going to be my parallax layers, and i am going to translate them.
I came up with something like this:
var parallax = {
target: {
x: Mouse.x,
y: Mouse.y
},
offset: {
x: -ctx.width / 2,
y: -ctx.height / 2
},
factor: {
x: 1,
y: 1
}
}
var angle = 0;
var zoomX = 1;
var zoomY = 1;
var loop = function(){
ctx.canvas.width = ctx.canvas.width; //Clear the canvas.
ctx.translate(parallax.target.x * parallax.factor.x, parallax.target.y * parallax.factor.y);
ctx.rotate(angle);
ctx.scale(zoomX, zoomY);
ctx.translate((-parallax.target.x - parallax.offset.x) * parallax.factor.x, (-parallax.target.y - parallax.offset.y) * parallax.factor.y);
Draw(); //Function that draws all the objects on the screen.
}
This is a very small and simplified part of my script, but i hope that's enough to get what i am doing. The object "parallax" contains the target position, the offset(the distance from the target), and the factor that is determining how fast the canvas is moving away relatively to the target. ctx is the canvas that is moving in the opposite direction of the target.(In this example i am using only one layer.) I am using the mouse as the "target", but i could also use the player, or some other object with x and y property. The target is also the point around which i rotate and scale the canvas.
This method works completely fine as long as the factor is equal to 1. If it is something else, the whole thing suddenly stops working correctly, and when i try to zoom, it zooms to the top-left corner, not the target. I also noticed that if i zoom out too much, the canvas is not moving in the opposite way of the target, but in the same direction.
So my question is: What is the correct way of implementing parallax with zooming and rotating?
P.S. It is important to me that i am using canvases as the layers.
To prepare for the next animation frame, you must undo any previous transforms in the reverse order they were executed:
context.translate(x,y);
context.scale(sx,sy);
context.rotate(r);
// draw stuff
context.rotate(-r);
context.scale(-sx,-sy);
context.translate(-x,-y);
Alternatively, you can use context.save / context.restore to undo the previous transforms.
Adjust your parallax values for the current frame,
Save the un-transformed context state using context.save(),
Do your transforms (translate, scale, rotate, etc),
Draw you objects as if they were in non-transformed space with [0,0] at your translate point,
Restore your context to it's untransformed state using context.restore()/
Either way will correctly give you a default-oriented canvas to use for your next animation frame.
The exact parallax effects you apply are up to your own design, but using these methods will make the canvas return to a normal default state for you to design with.

Calculate new width when skewing in canvas

I'm using canvas for a project and I have a number of elements that I'm skewing. I'm only skewing on the y value and just want to know what the new width of the image is after skewing (so I can align it with another canvas element). Check out the code below to see what I mean
ctx.save();
//skew the context
ctx.transform(1,0,1.3,0,0,0);
//draw two images with different heights/widths
ctx.drawImage(image,0,0,42,60);
ctx.drawImage(image,0,0,32,25);
The goal would be to know that the 42 by 60 image was now a X by 60 image so I could do some translating before drawing it at 0,0. It's easy enough to measure each image individually, but I have different skew values and heights/widths throughout the project that need to be align. Currently I use this code (works decently for images between 25 and 42 widths):
var skewModifier = imageWidth*(8/6)+(19/3);
var skewAmount = 1.3; //this is dynamic in my app
var width = (skewModifier*skewAmount)+imageWidth;
As images get wider though this formula quickly falls apart (I think it's a sloping formula not a straight value like this one). Any ideas on what canvas does for skews?
You should be able to derive it mathematically. I believe:
Math.atan(skewAmount) is the angle, in radians, that something is skewed with respect to the origin.
So 1.3 would skew the object by 0.915 radians or 52 degrees.
So here's a red unskewed object next to the same object skewed (painted green). So you have a right triangle:
We know the origin angle (0.915 rads) and we know the adjacent side length, which is 60 and 25 for your two images. (red's height).
The hypotenuse is the long side thats being skewed.
And the opposite side is the triangle bottom - how much its been skewed!
Tangent gets us opposite / adjacent if I recall, so for the first one:
tan(0.915) = opposite / 60, solving for the opposite in JavaScript code we have:
opposite = Math.tan(0.915)*60
So the bottom side of the skewed object starts about 77 pixels away from the origin. Lets check our work in the canvas:
http://jsfiddle.net/LBzUt/
Looks good to me!
The triangle in question of course is the canvas origin, that black dot I painted, and the bottom-left of the red rectangle, which is the original position that we're searching for before skewing.
That was a bit of a haphazard explanation. Any questions?
Taking Simon's fiddle example one step further, so you can simply enter the degrees:
Here's the fiddle
http://jsfiddle.net/LBzUt/33/

Categories