HTML5 Canvas and Line Width - html

I'm drawing line graphs on a canvas. The lines draw fine. The graph is scaled, every segment is drawn, color are ok, etc. My only problem is visually the line width varies. It's almost like the nib of a caligraphy pen. If the stroke is upward the line is thin, if the stroke is horizontal, the line is thicker.
My line thickness is constant, and my strokeStyle is set to black. I don't see any other properties of the canvas that affect such a varying line width but there must be.

Javascript:
var badCanvas = document.getElementById("badCanvas"),
goodCanvas = document.getElementById("goodCanvas"),
bCtx = badCanvas.getContext("2d"),
gCtx = goodCanvas.getContext("2d");
badCanvas.width = goodCanvas.width = badCanvas.height = goodCanvas.height = 300;
// Line example where the lines are blurry weird ect.
// Horizontal
bCtx.beginPath();
bCtx.moveTo(10,10);
bCtx.lineTo(200,10);
bCtx.stroke();
//Verticle
bCtx.beginPath();
bCtx.moveTo(30,30);
bCtx.lineTo(30,200);
bCtx.stroke();
// Proper way to draw them so they are "clear"
//Horizontal
gCtx.beginPath();
gCtx.moveTo(10.5,10.5);
gCtx.lineTo(200.5,10.5);
gCtx.stroke();
//Verticle
gCtx.beginPath();
gCtx.moveTo(30.5,30);
gCtx.lineTo(30.5,200);
gCtx.stroke();
// Change the line width
bCtx.lineWidth = 4;
gCtx.lineWidth = 4;
// Line example where the lines are blurry weird ect.
// Horizontal
bCtx.beginPath();
bCtx.moveTo(10,20.5);
bCtx.lineTo(200,20.5);
bCtx.stroke();
//Verticle
bCtx.beginPath()
bCtx.moveTo(50.5,30);
bCtx.lineTo(50.5,200);
bCtx.stroke();
// Proper way to draw them so they are "clear"
//Horizontal
gCtx.beginPath();
gCtx.moveTo(10,20);
gCtx.lineTo(200,20);
gCtx.stroke();
//Verticle
gCtx.beginPath();
gCtx.moveTo(50,30);
gCtx.lineTo(50,200);
gCtx.stroke();
HTML:
<h2>BadCanvas</h2>
<canvas id="badCanvas"></canvas>
<h2>Good Canvas</h2>
<canvas id="goodCanvas"></canvas>
CSS:
canvas{border:1px solid blue;}
Live Demo
My live demo basically just recreates what the MDN says. For even stroke widths you can use integers for coordinates, for odd stroke widths you want to use .5 to get crisp lines that fill the pixels correctly.
From MDN Article
If you consider a path from (3,1) to (3,5) with a line thickness of
1.0, you end up with the situation in the second image. The actual
area to be filled (dark blue) only extends halfway into the pixels on
either side of the path. An approximation of this has to be rendered,
which means that those pixels being only partially shaded, and results
in the entire area (the light blue and dark blue) being filled in with
a color only half as dark as the actual stroke color. This is what
happens with the 1.0 width line in the previous example code.
To fix this, you have to be very precise in your path creation.
Knowing that a 1.0 width line will extend half a unit to either side
of the path, creating the path from (3.5,1) to (3.5,5) results in the
situation in the third image — the 1.0 line width ends up completely
and precisely filling a single pixel vertical line.

If linewidth is an odd number, just add 0.5 to x or y.

I just solved a problem of a similar nature. It involved a bug in a For loop.
PROBLEM: I had created a for loop to create a series of connected line segments and noticed that the line was thick to start but thinned out significantly by the final segment (no gradients were explicitly used).
FIRST, DEAD END THOUGHT: At first I assumed it was the above pixel issue, but the problem persisted even after forcing all the segments to remain at a constant level.
OBSERVATION: I noticed that I made a newbie's mistake -- I only used a single "ctx.beginPath()" and "ctx.moveTo(posX,posY)" PRIOR to the For loop and a single "ctx.stroke()" AFTER the For loop and the loop itself wrapped a single ctx.lineTo().
SOLUTION: Once I moved all methods (.beginPath(), .moveTo(), .lineTo() and .stroke()) together into the For loop so they would all be hit on each iteration, the problem went away. My connected line had the desired uniform thickness.

Try lineCap = "round" and lineJoin = "round". See "Line Styles" in this PDF to see what these parameters do.
Edit 17-July-2015: Great cheat sheet, but the link is dead. As far as I can tell, there's a copy of it at http://www.cheat-sheets.org/saved-copy/HTML5_Canvas_Cheat_Sheet.pdf.

Related

Is there a way to determine whether there's a sufficient amount of space in a Pie chart segment for a label?

In the attached Google charts Pie chart the labels fit well inside the segments. Determining the length of a bit of text in HTML5 canvas is easy enough - but how do you determine whether the label will fit into a particular segment (using trigonometry) ? As you can see on the image, two of the segments don't have labels inside the segment.
EDIT: Here's an example of what I have at the moment: https://www.rgraph.net/tests/canvas.pie/in-pie-labels.html
As you see the labels for the small segments overlap. What I'm after is a way to calculate whether there's enough space for the labels at the point where they're going to be rendered. If not, I can just not draw the label like in the example image above.
Could chord size be useful to do this?
Here's the forumulae for the chord size that I found via Google:
"Chord length using trigonometry = 2 × r × sin(θ/2); where 'r' is the radius of the circle and 'θ' is the angle subtended at the center by the chord."
I sorted it (in about one hour) after 3 days of trying to calculate it with trig by using the built-in context.isPointInPath() function...
Draw the text (transparent color) to get the coordinates (x/y/w/h) of it. You might be able to get away with measuring it to get the width and height.
Draw the segment in a transparent color and do not stroke or fill it. Also, do not close the path.
Test each corner of the text rectangle (formed the x/y/w/h that you got above) using the context.isPointInPath() function. If the function returns true for each corner of the rectangle formed by the coordinates of the text, then the text will fit into the segment.

Why are there black lines between my sprites?

I have a single pixel sprite. To this sprite I add four sprites, each a quarter of a square. To offset the sprites, all i do is change their anchor points.
For example:
top right square is at anchor: (0,0);
bottom right : (0,1);
bottom left : (1,1);
top left : (1,0);
I expected the sprite edges to meet perfectly so that it looks like one big square. Instead there are black lines between the edges of each square so it looks like I have placed four squares close together.
I use texture packer to create a sprite sheet, containing the various squares.
Is there some setting in cocos2d-x or some code I must change to get the sprites to align perfectly ?
Edit: This is for cocos2d-x 3.1.1 and higher. Changing the anchor point is necessary and unavoidable.
EDIT: I use sprite frames from a sprite sheet created using TexturePacker. This was the problem. See my answer below.
The problem has something to do with using a sprite sheet (created using TexturePacker) to hold the pieces together. When you place the frames from the sprite sheet together to form a complete image the lines appear.
You can make the black lines disappear by setting the "Extrude" option in Texturepacker to at least 1.
EDIT: For those of you updating sprite positions based on a physics simulation, black lines can be caused by "sub pixel" positions. Try to either move your objects by complete pixels. Or search for answers with "sub pixel" for other solutions.
casting positions calculations to int type didn't help ?
Generally after certain float calculations like multiplying and divide and then complier auto demoting to to int may result in variation of 1px.
for example 26.500123 can be treated as pixel 26 or 27, depending to your casting methodology.
Test Case:
Are you saying you did this ?
auto testNode = Node::create();
auto s1 = Sprite::create("Images/1.png");
s1->cocos2d::Node::setAnchorPoint(Point(1,0));
auto s2 = Sprite::create("Images/2.png");
s2->cocos2d::Node::setAnchorPoint(Point(0,0));
auto s3 = Sprite::create("Images/3.png");
s3->cocos2d::Node::setAnchorPoint(Point(1,1));
auto s4 = Sprite::create("Images/4.png");
s4->cocos2d::Node::setAnchorPoint(Point(0,1));
testNode->addChild(s1);
testNode->addChild(s2);
testNode->addChild(s3);
testNode->addChild(s4);
testNode->setPosition(Point(screenSize.width/2,screenSize.height/2));
this->addChild(testNode);
and you got 1px gap ? i did that same with cocos2dx 3.1
i got this fine lady
Don't change anchorPoint, you'll regret it later. Calculate the correct position for each sprite.
Make sure the position x/y are on pixel boundaries. Casting to int will do the trick though Retina devices allow for 0.5 positions as well due to pixel density being 2x the point resolution.
Point #2 is also why you shouldn't use anchorPoint because you can't cast the position to integers when offsetting the texture with the anchorPoint.

Draw stroke on HTML canvas with different levels of opacity

The problem
I'm trying to create a brush tool with opacity jitter (like in Photoshop). The specific problem is:
Draw a stroke on an HTML canvas with different levels of opacity. Pixels with higher opacity should replace pixels with lower opacity; otherwise, pixels are left unchanged.
Transparency should not be lost in the process. The stroke is drawn on a separate canvas and merged with a background canvas afterwards.
The result should look like this. All code and the corresponding output can be found here (JSFiddle).
Because you can't stroke a single path with different levels of opacity (please correct me if I'm wrong) my code creates a path for each segment with different opacity.
Non-solution 1, Using the 'darken' blend mode
The darken blend mode yields the desired result when using opaque pixels but doesn't seem to work with transparency. Loosing transparency is a dealbreaker.
With opaque pixels:
With transparent pixels:
Non-solution 2, Using the 'destination-out' compositing operator
Before drawing a new stroke segment, subtract its opacity from subjacent pixels by using the 'destination-out' compositing operator. Then add the new stroke segment with 'source-over'. This works almost but it's a little bit off.
Looking for a solution
I want to avoid manipulating each pixel by hand (which I have done in the past). Am I missing something obvious? Is there a simple solution to this problem?
"Links to jsfiddle.net must be accompanied by code."
Because you can't stroke a single path with different levels of opacity (please correct me if I'm wrong)
You're wrong =)
When you use globalCompositeOperation = 'destination-out' (which you are in lineDestinationOut) you need to set the strokeStyle opacity to 1 to remove everything.
However, simply changing that in your fiddle doesn't have the required effect due to the order of your path build. Build the 10% transparent one first, the whole length, then delete and draw the two 40% transparent bits.
Here's a jsfiddle of the code below
var canvas = document.getElementById('canvas');
var cx = canvas.getContext('2d');
cx.lineCap = 'round';
cx.lineJoin = 'round';
cx.lineWidth = 40;
// Create the first line, 10% transparency, the whole length of the shape.
cx.strokeStyle = 'rgba(0,0,255,0.1)';
cx.beginPath();
cx.moveTo(20,20);
cx.lineTo(260,20);
cx.lineTo(220,60);
cx.stroke();
cx.closePath();
// Create the first part of the second line, first by clearing the first
// line, then 40% transparency.
cx.strokeStyle = 'black';
cx.globalCompositeOperation = 'destination-out';
cx.beginPath();
cx.moveTo(20,20);
cx.lineTo(100,20);
cx.stroke();
cx.strokeStyle = 'rgba(0,0,255,0.4)';
cx.globalCompositeOperation = 'source-over';
cx.stroke();
cx.closePath();
// Create the second part of the second line, same as above.
cx.strokeStyle = 'black';
cx.globalCompositeOperation = 'destination-out';
cx.beginPath();
cx.moveTo(180,20);
cx.lineTo(260,20);
cx.stroke();
cx.strokeStyle = 'rgba(0,0,255,0.4)';
cx.globalCompositeOperation = 'source-over';
cx.stroke();
cx.closePath();
Use two layers to draw to:
First calculate the top layer opacity 40% - 10% and set this as alpha on top layer
Set bottom layer to 10%
Set top layer with dashed lines (lineDash) (calculate the dash-pattern size based on size requirements)
Draw lines to both layers and the bottom layer will be a single long line, the top layer will draw a dashed line on top when stroked.
Copy both layers to main canvas when done.
#HenryBlyth's answer is probably the best you're going to get; there's no native API to do what you're being asked to do (which, in my opinion, is kinda weird anyways... opacity isn't really supposed to replace pixels).
To spell out the solution in one paragraph: Split up your "stroke" into individual paths with different opacities. Draw the lowest opacity paths as normal. Then, draw the higher opacities with "desitination-out" to remove the low-opacity paths that overlap. Then, draw the high opacity paths as usual, with "source-over", to create the effect desired.
As suggested in the comments to that answer, #markE's comment about making each path an object that is pre-sorted before drawing is a great suggestion. Since you want to perform manual drawing logic that the native API can't do, turning each path into an object and dealing with them that way will be far easier than manually manipulating each pixel (though that solution would work, it could also drive you mad.)
You mention that each stroke is being done on another canvas, which is great, because you can record the mouseevents that fire as that line is being drawn, create an object to represent that path, and then use that object and others in your "merged" canvas without having to worry about pixel manipulation or anything else. I highly recommend switching to an object-oriented approach like #markE suggested, if possible.

drawing a line: is there exists a limits of thickness in Graphics.lineStyle()?

I'm developing a simple a graphical editor for my flash-based app. In my editor there's a posibility of scaling, range of scaling is big (maximum scale is 16.0, minimum scale is 0.001 and default scale is 0.2). So it's quite possible that a user can draw a line with thickness 0.1 or 300.0, and it looks that line possible thickness (in Graphics.lineStyle()) has upper border. As I found out from livedocs maximum value is 255. So if thickness is greater then 255.0 there'is drawn a line of thickness 255.0. Whether mentioned upper border exists and how big is it. Here're my questions:
Right now I'm drawing lines with drawPath() or lineTo() methods. Natural walkarround if thickness is greater then 255.0 is to draw a rectange instead of segment and two circles on the ends of segment (instead of lineTo()). Or even to draw two thin segments and two half-circles and fill interior. Maybe there's more elegant/quick solution?
Another question is if the thickness of line is big but less then 255.0 (e.g. 100.0), what is faster drawing a line with lineTo() or drawing two thin segments and two half-circles and fill interior?
And finally, maybe someone knows a good article/book where I can read what's inside all methods of flash.display.Graphics class (or even not flash specific article/book on graphics)?
Any thoughts are appreciated. Thank you in advance!
I agree with f-a that putting the line in a container would probably be better and more efficient than drawing a rectangle and extra circles.
I don't think that the math would be too difficult to work out. For efficiency you should probably only do this if the line style is going to be over 255.
To setup the display object to hold your line I would start by halving the width of your line (the length can stay the same). Then create a new sprite and draw the line in the sprite at half size (e.g. if you wanted 300, just draw it at 150). It would be most simple to just start at (0,0) and draw the segment straight so that all of your transformations can be applied to the new sprite.
From here you can just double the scaleY of the sprite to get the desired line weight. It should keep the same length and the ends should also be rounded correctly.
Hope this helped out!
A cool resource for working with the graphics class is Flash and Math. This site has several cool effects and working examples and source code.
http://www.flashandmath.com/

How do I create and distribute diagonal stripes on a rectangle?

I would like to be able to create bar charts with JFreeChart that looks similar to the following picture.
It is a very basic mono-colored bar chart, but with one "fancy" detail: the diagonal stripes. I was thinking that this could be made possible by overlaying another picture on top of the normal bar. This picture would have the same dimensions as the bar, have diagonal white stripes and a transparent background. I am not quite sure how to do this though, as I have very little GUI experience, but I found a very useful article that deals with overlaying images on top of graphics from JFreeChart, so I am quite certain I should be able to pull that of.
But how should I create the diagonal stripes?
I see how I could distribute the lines from the lower left corner to the upper right corner, but not the capped lines in the upper left and lower right corner. Can I somehow paint outside the rectangle (and not have it included in the picture)?
edit: After some searching I cannot see that my suggestion of overlaying an image with a transparent background would work, as I cannot find any examples on how to do this. On the other hand, merely painting the lines on the rectangle is probably easier.
Using a gradient fill to draw lines
On trashgod's tip I tried filling a shape with a gradient that had sharp edges to simulate line drawing. This would prevent a lot of calculations and could potentially be a lot simpler. It worked quite ok for thick lines, but not for thinner lines. Using the following code produces the fill in the first picture:
rect.setSpace(spaceBetweenLines);
Color bg = Color.YELLOW;
Color fg = Color.BLUE;
rect.setPaint(new LinearGradientPaint(
(float) startX, (float) startY, (float) (startX + spaceBetweenLines), (float) (startY + spaceBetweenLines),
new float[] {0,.1f,.1001f}, new Color[] {fg,fg,bg}, MultipleGradientPaint.CycleMethod.REPEAT)
);
Drawing lines using graphic primitives
Although simpler it did not work in my case. The more elaborate, but to me, more natural way of doing it, is simply drawing lines on top of the shape (rectangle, cirle, ...). The following code was used in producing the second image. Observe the use of the clip(Shape s) to restrict the line drawing to the shape underneath. The reason for not simply drawing a rectangle and using clip() to limit the shape is that the clip() operation is not aliased, thus producing jaggies. Therefore I have to draw the shape first to get smooth edges, then set the clip to prevent overflow in the forthcoming line drawing, and finally draw the lines.
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(getBackground());
g2.fill(getShape());
g2.setClip(getShape());
// draw diagonal lines
g2.setPaint(getLineColor());
for (int x = (int) this.x, y = (int) (this.y); y - height < (this.y + height + getSpace()); ) {
g2.drawLine(x, y , x + (int) width , y - (int) width);
y += getSpace();
}
The source code for BarChartDemo1 shows how to apply a GradientPaint, but you may want to experiment with LinearGradientPaint to get the diagonal effect.
I want to paint the bars, not the background.
If you already have a suitable image, TexturePaint may be an alternative.