canvas. Unexpected ends of the line - javascript

I need to get a picture like this:
context.beginPath();
context.moveTo(20, 20);
context.lineTo(120, 70);
context.lineTo(220, 20);
context.lineWidth = 15;
context.stroke();
context.fillStyle = 'aqua';
context.fill();
But as a result, I get this picture:
Is it possible to get rid of such unexpected ends of the line?

In this particular case, you can just clear the rectangle above the triangle, as shown below.
The issue in general is that you're drawing a 15-unit-wide line centered along the triangle's edge; you'd have to compute how much to extend the line outside the triangle and halve its width, or to compute a similar filled polygon, to make this work in the general case.
var canvas = document.getElementById("c");
var context = canvas.getContext("2d");
context.beginPath();
context.moveTo(20, 20);
context.lineTo(120, 70);
context.lineTo(220, 20);
context.lineWidth = 15;
context.stroke();
context.fillStyle = 'aqua';
context.fill();
context.clearRect(10, 10, 210, 10);
<canvas id="c" width="240" height="100">

Related

How to make only two shapes compost together in HTML canvas without effecting other shapes

So my goal is simple... I think. I want to draw a rectangle with a hole cut out in the middle. But I don't want that hole to go through anything else on the canvas.
Right now I have something like this:
context.fillStyle = 'blue';
context.fillRect(0, 0, width, height);
context.fillStyle = "#000000";
context.beginPath();
context.rect(0, 0 , width, height);
context.fill();
enter code here
context.globalCompositeOperation="destination-out";
context.beginPath();
context.arc(width / 2, height / 2 , 80, 0, 50);
context.fill();
But this also cuts through the background as well, how would I make it only cut through the black rectangle and nothing else?
Visual Example in case I'm not explaining well:
Take a look at this see if that is what you are looking for:
<canvas id="canvas" width="200" height="160"></canvas>
<script>
class Shape {
constructor(x, y, width, height, color) {
this.color = color
this.path = new Path2D();
this.path.arc(x, y, height / 3, 0, 2 * Math.PI);
this.path.rect(x + width / 2, y - height / 2, -width, height);
}
draw(ctx) {
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.fill(this.path);
}
}
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
shapes = [];
shapes.push(new Shape(40, 40, 80, 80, "blue"));
shapes.push(new Shape(60, 65, 70, 70, "red"));
shapes.push(new Shape(80, 40, 65, 65, "gray"));
shapes.forEach((s) => {
s.draw(ctx);
});
</script>
I'm using a Path2D() because I had a quick example from something I did before, but that should be doable without it too. The theory behind is simple, we just want to fill the opposite on the circle.
I hard coded the radius to a third of the height, but you can change all that to something else or even be a parameter the final user can change
Is this what you were hoping to achieve?
const context = document.getElementById("canvas").getContext('2d');
const width = 100;
const height = 100;
const circleSize = 30;
context.fillStyle = "black";
context.fillRect(0, 0 , width, height);
context.beginPath();
context.arc(width / 2, height / 2, circleSize, 0, 2 * Math.PI);
context.clip();
context.fillStyle = "blue";
context.fillRect(0, 0, width, height);
<canvas id="canvas"/>
This article might be useful:
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing
In the example above, I'm using clip.
As the documentation states:
The CanvasRenderingContext2D.clip() method of the Canvas 2D API turns the current or given path into the current clipping region.
This means that any element added to the context after this line, will only be drawn within that clipped path.

How to draw in canvas 2D this shape and fill it with color?

This should be without this diagonal. I want to draw two arcs one with x2 smaller radius, join them and fill(). I know how to calculate the end and beginning of an arc, problem is arcs are always drawn clockwise, so to draw second arc within same ctx.beginPath() I have to use something like ctx.moveTo() but problem with moveTo is I get two different paths as proof closePath() cause this diagonal.
So I want to know how to draw arc in other direction than clockwise or how to use moveTo() but still beeing able to fill this shape. Filling now cause following issue:
White diagonal visible.
Arcs are not always drawn clockwise. The sixth parameter to .arc is a boolean which when true will make the arc be drawn anti-clockwise.
However you will also need to reverse the start and end angles, otherwise the arc will attempt to go the long way around:
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(20, 20, 40, 30 * Math.PI / 180, 80 * Math.PI / 180);
ctx.arc(20, 20, 150, 80 * Math.PI / 180, 30 * Math.PI / 180, true);
ctx.closePath();
ctx.lineWidth = 3;
ctx.stroke();
ctx.fillStyle = '#e0e0ff';
ctx.fill();
<canvas id="c" width="200" height="200" />
Why not use the lineWidth property to make the arc thicker. In this case you'll only need one call to arc:
let canvas = document.getElementById("canvas"),
context = canvas.getContext("2d");
context.beginPath();
context.arc(20, 20, 40, 0, Math.PI / 4);
context.lineWidth = 15;
context.stroke();
<canvas id="canvas"></canvas>

Overwrite drawn over canvas when drawing transparent shapes

I can't see that this had been posted already, so here goes.
Let's say i draw 2 squares on the canvas.
var c = document.getElementById('test'), ctx = c.getContext('2d');
ctx.fillStyle = "rgba(0,0,255,0.5)";
ctx.beginPath();
ctx.moveTo(25, 0);
ctx.lineTo(50, 50);
ctx.lineTo(0, 50);
ctx.lineTo(25, 0);
ctx.fill();
ctx.fillStyle = "rgba(255,0,0,0.5)";
ctx.beginPath();
ctx.moveTo(50, 0);
ctx.lineTo(75, 50);
ctx.lineTo(25, 50);
ctx.lineTo(50, 0);
ctx.fill();
This produces this image:
If i change globalAlpha to 0.5, i get this:
However, i want to produce this:
As in, all pixels are transparent and any images under it will appear, but the pixels created by the red triangle will overwrite the existing blue triangle where it is drawn.
And ctx.globalComposisteOperation doesn't seem to help in this instance due to it also factoring the transparency and the fact i want to keep both squares.
Is there any way to do this with current methods?
Use Compositing to clear the red triangle before drawing it.
Using compositing is slightly better than clipping because you don't have to clear the clip. Clearing a clip requires saving the entire context state and then restoring that context state -- many properties involved. Compositing just requires changing 1 property forth and back.
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
// fill the blue rect
ctx.fillStyle = "rgba(0,0,255,0.5)";
ctx.beginPath();
ctx.moveTo(25, 0);
ctx.lineTo(50, 50);
ctx.lineTo(0, 50);
ctx.lineTo(25, 0);
ctx.fill();
// define the red rect path
ctx.beginPath();
ctx.moveTo(50, 0);
ctx.lineTo(75, 50);
ctx.lineTo(25, 50);
ctx.lineTo(50, 0);
// clear the red rect path using compositing
ctx.globalCompositeOperation='destination-out';
ctx.fillStyle='black';
ctx.fill();
ctx.globalCompositeOperation='source-over';
// fill the red rect
ctx.fillStyle = "rgba(255,0,0,0.5)";
ctx.fill();
body{ background-color:white; }
#canvas{border:1px solid red; }
<canvas id="canvas" width=512 height=512></canvas>
Layers
Do it the photoshop way and create layers to do the work for you. Creating a layer (second canvas) is no more trouble than loading an image. You can create dozens and have no problem and it makes this type of work easy.
First create a second canvas (layer)
// canvas is original canvas
var layer = document.createElement("canvas");
layer.width = canvas.width; // same size as original
layer.height = canvas.height;
var ctx1 = layer.getContext("2d");
Then draw your triangles on the second canvas with alpha = 1;
var tri = (x,c)=>{
ctx1.fillStyle = c;
ctx1.beginPath();
ctx1.moveTo(25 + x, 0);
ctx1.lineTo(50 + x, 50);
ctx1.lineTo(0 + x, 50);
ctx1.closePath();
ctx1.fill();
}
tri(0,"#00f");
tri(25,"#f00");
Then just draw that layer on top of the canvas you are working on with the alpha value you want.
ctx.globalAlpha = 0.5;
ctx.drawImage(layer,0,0);
If you don't need the extra layer delete the canvas and context by dereferencing them.
ctx1 = undefined;
layer = undefined;
Or you can keep the layer , and make another layer for the background and mix them in real time to get the FX just right
//
var canvas = document.createElement("canvas");
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");
var layer = document.createElement("canvas");
layer.width = canvas.width; // same size as original
layer.height = canvas.height;
var ctx1 = layer.getContext("2d");
var tri = (x,c)=>{
ctx1.fillStyle = c;
ctx1.beginPath();
ctx1.moveTo(25 + x, 0);
ctx1.lineTo(50 + x, 50);
ctx1.lineTo(0 + x, 50);
ctx1.fill();
}
tri(0,"#00f");
tri(25,"#0f0");
tri(50,"#f00");
ctx.globalAlpha = 0.5;
ctx.drawImage(layer,0,0);
layer = ctx1 = undefined;
You can clear the area for the second rectangle before drawing it.
var c = document.getElementById('game'),
ctx = c.getContext('2d');
ctx.globalAlpha = 0.5;
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, 50, 50);
// Clear the extra bit of the blue rectangle
ctx.clearRect(25, 25, 25, 25);
ctx.fillStyle = "red";
ctx.fillRect(25, 25, 50, 50);
<canvas id="game" width="320" height="240"></canvas>
I would honestly suggest just changing the colors and avoid using an alpha.
var c = document.getElementById('game'),
ctx = c.getContext('2d');
ctx.fillStyle = "#8080FF";
ctx.fillRect(0, 0, 50, 50);
ctx.fillStyle = "#ff8080";
ctx.fillRect(25, 25, 50, 50);
<canvas id="game" width="320" height="240"></canvas>
var c = document.getElementById('test'), ctx = c.getContext('2d');
ctx.save();
ctx.fillStyle = "rgba(0,0,255,0.5)";
ctx.beginPath();
ctx.moveTo(25, 0);
ctx.lineTo(50, 50);
ctx.lineTo(0, 50);
ctx.lineTo(25, 0);
ctx.fill();
ctx.fillStyle = "rgba(255,0,0,0.5)";
ctx.beginPath();
ctx.moveTo(50, 0);
ctx.lineTo(75, 50);
ctx.lineTo(25, 50);
ctx.lineTo(50, 0);
ctx.clip();
ctx.clearRect(0, 0, 100, 100);
ctx.fill();
ctx.restore();
Just use clip() to take the current path, clear everything in there with clearRect, then draw the path as normal.
#markE is right, use compositing instead of clipping (really heavy).
However, his solution will only work if you've drawn everything with an rgba color. Maybe I read your question wrongly, but if you're going from an opaque shape and want to make it transparent, then you should rather use the copy gCO and the globalAlpha property.
This will have less performance impact since drawImage is faster than fill, and will allow you to perform a fade-out effect ; but it really depends on your needs.
var ctx = c.getContext('2d');
// initial blue
ctx.fillStyle = "#0000FF";
ctx.beginPath();
ctx.moveTo(25, 0);
ctx.lineTo(50, 50);
ctx.lineTo(0, 50);
ctx.lineTo(25, 0);
ctx.fill();
setTimeout(function drawRed() {
ctx.fillStyle = "#FF0000";
ctx.beginPath();
ctx.moveTo(50, 0);
ctx.lineTo(75, 50);
ctx.lineTo(25, 50);
ctx.lineTo(50, 0);
ctx.fill();
}, 500);
btn.onclick = function makeItTransparent() {
// if we weere to make this into an animation, we would set it only once
ctx.globalCompositeOperation = 'copy';
ctx.globalAlpha = .8;
// draw the canvas on itself
ctx.drawImage(c, 0, 0);
// once again, in an animation we won't reset this to default
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = 'source-over';
};
/* checkboard background */
canvas {
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAGElEQVQYlWNgYGBowIKxgqGgcJA5h3yFAOI3GQFqqi5ZAAAAAElFTkSuQmCC");
}
<canvas id="c"></canvas>
<button id="btn">make it transparent</button>

Canvas polygons not touching properly

So I've been fiddling with the canvas element, and I seem to have run into a situation that is highly irritating, yet I haven't been able to find a solution.
Say that two polygons are drawn on a canvas, and that they should be touching each other. Where one polygon is drawn like this:
ctx.beginPath();
ctx.moveTo(oX,oY);
ctx.lineTo(oX=oX+k,oY=oY-h);
ctx.lineTo(oX=oX+k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY-h);
ctx.fill();
A simple version is implemented in this fiddle.
As you can probably see there is a thin line between these shapes. How can I avoid it? I have tried the solutions here, but they don't really seem to refer to this case, because I'm dealing with diagonal lines.
One solution
You could always use the stroke-line trick, but depending on your goal:
If it is to show many polygons next to each other, you could look at the polygons as simple squares.
Draw them in as such in an off-screen canvas next to each other. This will produce a result with no gaps.
Then transform the main canvas into the position you want those polygons to appear. Add rotation and/or skew depending on goal.
Finally, draw the off-screen canvas onto the main canvas as an image. Problem gone.
This will give you an accurate result with no extra steps in stroking, and the calculations for the boxes becomes very simple and fast to do (think 2d grid).
You have to use an off-screen canvas though. If you transform main canvas and draw in the shapes you will encounter the same problem as already present. This is because each point is transformed and if there is need for interpolation it will be calculated for each path shape separately. Drawing in an image will add interpolation on the whole surface, and only where there are gaps (non-opaque alpha). As we already are "gap-free" this is no longer a problem.
This will require an extra step in planning to place them correctly, but this is a simple step.
Example
Step 1 - draw boxes into an off-screen canvas:
This code draws on the off-screen canvas resulting in two boxes with no gap:
(the example uses an on-screen to show result, see next step for usage of off-screen canvas)
var ctx = document.querySelector("canvas").getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 50, 50);
ctx.fillRect(60, 10, 50, 50);
<canvas/>
Step 2 - transform main canvas and draw in off-screen canvas
When drawn into main canvas with transformation set, the result will be (pseudo-random transformation just to show):
var ctx = document.querySelector("canvas").getContext("2d");
// off-screen canvas
var octx = document.createElement("canvas").getContext("2d");
octx.fillStyle = "red";
octx.fillRect(10, 10, 50, 50);
octx.fillRect(60, 10, 50, 50);
// transform and draw to main
ctx.translate(80, 0);
ctx.rotate(0.5, Math.PI);
ctx.transform(1, 0, Math.tan(-0.5),1, 0,0); // skew
ctx.drawImage(octx.canvas, 0, 0);
<canvas />
Step 3 (optional) - Interaction
If you want to interact with the boxes you simply apply the same transform, then add path for a box and hit-test it against the mouse position. Redraw a single state, erase by clearing and draw back the off-screen canvas on top:
var ctx = document.querySelector("canvas").getContext("2d");
// off-screen canvas
var octx = document.createElement("canvas").getContext("2d");
octx.fillStyle = "red";
octx.fillRect(10, 10, 50, 50);
octx.fillRect(60, 10, 50, 50);
// allow us to reuse some of the steps:
function getTransforms() {
ctx.setTransform(1,0,0,1,0,0);
ctx.translate(80, 0);
ctx.rotate(0.5, Math.PI);
ctx.transform(1, 0, Math.tan(-0.5),1, 0,0); // skew
}
function clear() {
ctx.setTransform(1,0,0,1,0,0);
ctx.clearRect(0,0,300,150);
}
function redraw() {
ctx.drawImage(octx.canvas, 0, 0);
}
getTransforms();
redraw();
ctx.canvas.onmousemove = function(e) {
var r = this.getBoundingClientRect(),
x = e.clientX - r.left, y = e.clientY - r.top;
// box 1 (for many, use array)
ctx.beginPath();
ctx.rect(10, 10, 50, 50);
clear(); // these can be optimized to use state-flags
getTransforms(); // so they aren't redraw for every move...
redraw();
// just one box check here
if (ctx.isPointInPath(x, y)) {
ctx.fill();
}
};
<canvas />
Yes, it's annoying when filled polygons result in that tiny gap. It's especially common on diagonals that should theoretically meet.
A common workaround is to put a half-pixel, same-colored stroke around the polygons:
//Some basic setup ...
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var oX = 50;
var oY = 50;
var h = 33;
var k = 50;
ctx.fillStyle = 'red';
ctx.strokeStyle='red';
ctx.lineWidth=0.50;
//Draw one polygon
ctx.beginPath();
ctx.moveTo(oX,oY);
ctx.lineTo(oX=oX+k,oY=oY-h);
ctx.lineTo(oX=oX+k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY-h);
ctx.fill();
ctx.stroke();
//Draw another polygon
oX = oX+k;
oY = oY+h;
ctx.beginPath();
ctx.moveTo(oX,oY);
ctx.lineTo(oX=oX+k,oY=oY-h);
ctx.lineTo(oX=oX+k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY-h);
ctx.fill();
ctx.stroke();
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
//Some basic setup ...
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var oX = 50;
var oY = 50;
var h = 33;
var k = 50;
ctx.fillStyle = 'red';
ctx.strokeStyle='red';
ctx.lineWidth=0.50;
//Draw one polygon
ctx.beginPath();
ctx.moveTo(oX,oY);
ctx.lineTo(oX=oX+k,oY=oY-h);
ctx.lineTo(oX=oX+k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY-h);
ctx.fill();
ctx.stroke();
//Draw another polygon
oX = oX+k;
oY = oY+h;
ctx.beginPath();
ctx.moveTo(oX,oY);
ctx.lineTo(oX=oX+k,oY=oY-h);
ctx.lineTo(oX=oX+k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY-h);
ctx.fill();
ctx.stroke();
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>

Getting single shadow for fill and stroke on HTML canvas

I have to draw a stroked fill on canvas. For this I call ctx.fill and ctx.stroke separately. Due to this, the shadow of the stroke draws on top of the fill which I want to avoid.
Could somebody please tell if there is a way to avoid this?
Here is my code:
ctx1.fillStyle = "blue";
ctx1.strokeStyle = "black";
ctx1.shadowColor = "rgba(0,255,0, 1)";
ctx1.shadowOffsetX = 50;
ctx1.shadowOffsetY = 50;
ctx1.lineWidth = "20";
ctx.beginPath();
ctx.moveTo(300, 100);
ctx.lineTo(400, 100);
ctx.lineTo(400, 200);
ctx.lineTo(300, 200);
ctx.closePath();
ctx1.fill();
ctx1.stroke();
http://jsfiddle.net/abWYZ/3/
Every time you perform a draw action on the context the shadow is also drawn. The way canvas works is every thing that's drawn is placed on top of what was previously there. So whats happening is the fill is performed, making a shadow of it, and then the stroke is drawn, which makes a shadow on top of all previous drawn objects.
Here is one possible solution.
Live Demo
// Grab the Canvas and Drawing Context
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
ctx.save();
ctx.fillStyle = "blue";
ctx.strokeStyle = "black";
ctx.lineWidth="20";
ctx.beginPath();
ctx.moveTo(300, 100);
ctx.lineTo(400, 100);
ctx.lineTo(400, 200);
ctx.lineTo(300, 200);
ctx.closePath();
ctx.shadowColor = "rgba(0,255,0, 1)";
ctx.shadowOffsetX = 50;
ctx.shadowOffsetY = 50;
ctx.stroke();
ctx.fill();
// clear the shadow
ctx.shadowColor = 0;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
// restroke w/o the shadow
ctx.stroke();
If you use an approach like this I suggest making a function called toggleShadow or something along those lines allowing you to control when the shadows are drawn.

Categories

Resources