creating multiple clipping paths in HTML5 canvas using loop - javascript

I cannot create multiple clipping paths in canvas. With this code, if i=1, I get the clipping path working correctly. For i>1, I only see clipping if the paths are overlapping. Otherwise, nothing is drawn to the canvas.
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
for (var i = 0; i < 5; i++) {
ctx.beginPath();
var x = 25 + 25 * i; // x coordinate
var y = 75; // y coordinate
var radius = 20; // Arc radius
var startAngle = 0; // Starting point on circle
var endAngle = Math.PI * 2; // End point on circle
var anticlockwise = true; // clockwise or anticlockwise
ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
ctx.clip();
}
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 800, 150);
}
If it is not possible to have multiple clipping masks on the canvas, is there another compositing method that is the same as clipping mask?

If you wish to have multiple shapes in your clip area you need to define all the shapes then apply the clip. If you set the clip after adding each shape you end up clipping only inside the previous clip.
So move ctx.clip() to after the for loop, it need only be called once, and move the ctx.beginPath() to before the loop.

Related

html5 canvas draw lines in a circle

I am having some trouble drawing lines in circle with html5 canvas.
I am trying to make the bars look something like this
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
var bars = 50;
var radius = 100;
for(var i = 0; i < bars; i++){
var x = radius*Math.cos(i);
var y = radius*Math.sin(i);
draw_rectangle(x+200,y+200,1,13,i, ctx );
}
function draw_rectangle(x,y,w,h,deg, ctx){
ctx.save();
ctx.translate(x, y);
ctx.rotate(degrees_to_radians(deg));
ctx.fillStyle = "yellow";
ctx.fillRect(-1*(w/2), -1*(h/2), w, h);
ctx.restore();
}
function degrees_to_radians(degrees){
return degrees * Math.PI / 180;
}
function radians_to_degrees(radians){
return radians * 180 / Math.PI;
};
for some reason my lines are all crooked and unaligned. I really need help on this one. https://codepen.io/anon/pen/PRBdYV
The easiest way to deal with such a visualization is to play with the transformation matrix of your context.
You need to understand it as if you were holding a sheet of paper in your hands.
Instead of trying to draw the lines at the correct angle, rotate the sheet of paper, and always draw your lines in the same direction.
This way all you need in your drawing method is the angle, and the height of each bar.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
// the position of the whole thing
var circleX = canvas.width / 2;
var circleY = canvas.height / 2;
//
var bars = 50;
var barWidth = 5;
// inner radius
var radius = 50;
ctx.fillStyle = "yellow";
// no need to use degrees, a full circle is just 2π
for(var i = 0; i < Math.PI*2; i+= (Math.PI*2 / bars)){
draw_rectangle(i, (Math.random()*30) + 10);
}
function draw_rectangle(rad, barHeight){
// reset and move to the center of our circle
ctx.setTransform(1,0,0,1, circleX, circleY);
// rotate the context so we face the correct angle
ctx.rotate(rad);
// move along y axis to reach the inner radius
ctx.translate(0, radius);
// draw the bar
ctx.fillRect(
-barWidth/2, // centered on x
0, // from the inner radius
barWidth,
barHeight // until its own height
);
}
canvas#canvas{
background:black;
}
<html>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
</body>
</html>
https://codepen.io/anon/pen/YajONR
Problems fixed: Math.cos wants radians, not degrees
We need to go from 0 to 360, so I adjusted the number of bars to make that a bit easier, and multiplied i by 6 (so the max value is 60*6==360)
If we don't add +90 when drawing the bars, we just get a circle
Check your codepen and figured out the problem lies in the degrees_to_radians
Here is the update link of you code.Link
PS I only looked at the shape of the circle not alignments of the bar :D

Trying to animate shapes in canvas, it shows up, but doesn't move

I'm trying to animate polygons made using lineTo in canvas. It shows up, but won't move. I tried to follow the object approach, but it didn't seem to do anything.
Help?
<!doctype html>
<html>
<head>
<style>
canvas {
border: 1px solid black;
}
</style>
<script>
"use strict";
var canvas;
var ctx;
var timer;
var shapes;
var x;
var y;
function degreesToRadians(degrees) {
return (degrees*Math.PI)/180;
}
//to rotate stuff, not currently in use
function rotateStuff() {
roTimer = setInterval(ctx.rotate(degreesToRadians(60)),100);
}
//constructor for Shape object, not currently in use
function Shape() {
//this.x = canvas.width/2 + Math.random()*10-5;
//this.y = canvas.height/2 + Math.random()*10-5;
this.r = Math.random()*20-5;
this.vx = Math.random()*10-5;
this.vy = Math.random()*10-5;
var colors = ['red','green','orange','purple','blue','aqua','pink','gold'];
this.color = colors[Math.floor(Math.random()*colors.length)];
}
//pushes the shapes to an array, not currently in use
function makeShapes() {
shapes = [];
for (var i = 0; i<2; i++){
shapes.push(new Shape());
}
}
//fills and resets background
function fillBackground() {
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = 'rgba(0,0,0,0.3)';
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.globalCompositeOperation = 'lighter';
}
//draws the shape
function drawShapes(r, p, m) {
//canvas, x position, y position, radius, number of points, fraction of radius for inset
fillBackground();
x = 350;
y = 350;
r = Math.random()*20-5;
//for (var i = 0; i < shapes.length; i++) {
//var s = shapes[i];
ctx.save();
ctx.beginPath();
ctx.translate(x, y);
ctx.moveTo(0,0-r);
//}
for (var i2 = 0; i2 < p; i2++) {
ctx.rotate(Math.PI / p);
ctx.lineTo(0, 0 - (r*m));
ctx.rotate(Math.PI / p);
ctx.lineTo(0, 0 - r);
}
ctx.fillStyle = "yellow";
ctx.fill();
var vx = Math.random()*10-5;
var vy = Math.random()*10-5;
x += vx;
y += vy;
r -=8
ctx.restore();
}
//}
window.onload = function() {
canvas = document.getElementById('animCanvas');
ctx = canvas.getContext('2d');
//makeShapes();
//console.log(shapes);
timer = setInterval(drawShapes(40, 5, 0.5), 100);
//timer2 = setInterval(makeShapes, 4500);
}
</script>
</head>
<body>
<canvas width='700' height='700' id='animCanvas'></canvas>
</body>
</html>
A coding hint: Separate your code into discrete duties. This separation lets you concentrate your coding focus on simpler tasks. And once you've got that task running correctly you can move onto another task without worrying that a previous task has become broken.
Here are the tasks for your "rotate stars" project
1. Draw a star and
2. Rotate that star using animation.*
... and their descriptions
drawShapes() draws one star at a specified [x,y] position at a specified currentAngle
animate() runs an animation loop that:
Clears the canvas.
Fills the background.
Draws the star (or many stars) with `drawShapes`.
Changes the `currentAngle` rotation for the next loop.
Requests another animation loop.
About rotating
Rotating your shape is a simple 2 step process:
1. Move to the shape's centerpoint: `.translate(centerX,centerY)'
2. Rotate the canvas to the currently desired angle: `rotate(currentAngle)`
Since translate and rotate are not automatically undone, you must "clean up" after your transformations. An easy way to do that is to do this: context.setTransform(1,0,0,1,0,0). This sets the internal transformation matrix to its default state (==fully untransformed).
So your rotation process becomes:
1. Move to the shape's centerpoint: `.translate(centerX,centerY)'
2. Rotate the canvas to the currently desired angle: `.rotate(currentAngle)`
3. Reset the canvas: `.setTransform(1,0,0,1,0,0)`
Here's annotated code and a Demo:
var canvas;
var ctx;
canvas = document.getElementById('animCanvas');
ctx = canvas.getContext('2d');
var cw=canvas.width;
var ch=canvas.height;
var shapes=[];
var star1={ x:50, y:100, r:40, currentAngle:0, p:5, m:.5, fill:'yellow',angleChange:Math.PI/60}
var star2={ x:150, y:100, r:25, currentAngle:0, p:55, m:5, fill:'blue',angleChange:-Math.PI/360}
var star3={ x:250, y:100, r:25, currentAngle:0, p:15, m:3, fill:'red',angleChange:Math.PI/120}
requestAnimationFrame(animate);
function drawShapes(star) {
ctx.save();
// translate to the star's centerpoint
ctx.translate(star.x,star.y);
// rotate to the current angle
ctx.rotate(star.currentAngle)
// draw the star
ctx.beginPath();
ctx.moveTo(0,0-star.r);
for (var i2 = 0; i2 < star.p; i2++) {
ctx.rotate(Math.PI / star.p);
ctx.lineTo(0, 0 - (star.r*star.m));
ctx.rotate(Math.PI / star.p);
ctx.lineTo(0, 0 - star.r);
}
ctx.fillStyle =star.fill;
ctx.fill();
ctx.restore();
}
function fillBackground() {
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = 'rgba(0,0,0,0.3)';
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.globalCompositeOperation = 'lighter';
}
function animate(time){
// clear the canvas
ctx.clearRect(0,0,cw,ch);
// fill the background
fillBackground();
// draw the stars
// If you put star1,star2,star3 in a stars[] array then
// you could simply the following demo code by looping
// through the array
//
// draw the star1
drawShapes(star1);
// increase star1's current rotation angle
star1.currentAngle+=star1.angleChange;
// draw the star2
drawShapes(star2);
// increase star2's current rotation angle
star2.currentAngle+=star2.angleChange;
// draw the star3
drawShapes(star3);
// increase star3's current rotation angle
star3.currentAngle+=star2.angleChange;
// request another animation loop
requestAnimationFrame(animate);
}
<canvas width='700' height='700' id='animCanvas'></canvas> </body>

Rotating element on canvas object, relative to parent

I'm trying to draw a pair of skis (two rectangles) on a skier (a square) at varying rotations. I don't quite understand how you line up rotated elements on a canvas as you rotate the whole canvas, not just the object.
At the moment I have this:
ctx.fillStyle = 'rgba(0,0,0,0.8)';
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = skiier.color;
ctx.fillRect(skiier.x, skiier.y, skiier.width, skiier.height);
ctx.fillStyle = '#00f';
var angle = 20;
ctx.rotate(angle*Math.PI/180);
ctx.fillRect(skiier.x, skiier.y,100,10);
ctx.fillRect(skiier.x, skiier.y + 20,100,10);
ctx.rotate(-angle*Math.PI/180);
Which gives me this:
But what I'd like to do is the following:
Bearing in mind the x and y coords of the skier is constantly changing, how can I adjust and position the skis relative to him?
I have a demo here if it helps:
http://codepen.io/EightArmsHQ/pen/cfa7052ed205b664b066450910c830c5?editors=001
You should consider the context save, restore and translate as follows:
// ...
var angle = 20;
ctx.save(); // save the state of the ctx
ctx.translate(skiier.x, skiier.y); // translate your context point to be the same as skiier.
ctx.rotate(angle * Math.PI / 180);
ctx.fillRect(-25, 0, 100, 10); // You can draw from new context point.
ctx.fillRect(-25, 20, 100, 10); // Same here.
// Instead of rotating back, use restore()...
// Useful to restore all ctx options as they were before the save()
ctx.restore();
To rotate around a point: you need to translate context to the point, rotate context, translate context back.
For example...
ctx.fillStyle = 'rgba(0,0,0,0.8)';
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = skiier.color;
ctx.fillRect(skiier.x, skiier.y, skiier.width, skiier.height);
ctx.fillStyle = '#00f';
var angle = 20;
ctx.translate(skiier.x, skiier.y);
ctx.rotate(angle*Math.PI/180);
ctx.translate(-skiier.x, -skiier.y);
ctx.fillRect(skiier.x, skiier.y,100,10);
ctx.fillRect(skiier.x, skiier.y + 20,100,10);
ctx.rotate(-angle*Math.PI/180);

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>

Canvas animation pixelated

I want to animate an Arc on Canvas, and it works (with a really basic animation, interval), but the outcome is very pixelated/edgy. On the left side I draw an arc (animated), on the right side without animation (smooth).
JsFiddle: http://jsfiddle.net/C8CXz/2/
function degreesToRadians (degrees) {
return degrees * (Math.PI/180);
}
function radiansToDegrees (radians) {
return radians * (180/Math.PI);
}
var canvas = document.getElementById('circle');
var ctx = canvas.getContext('2d');
var start = 0, end = 0;
var int = setInterval(function(){
end++;
ctx.beginPath();
ctx.arc(80, 80, 50, degreesToRadians(0)-Math.PI/2, degreesToRadians(end)-Math.PI/2, false);
ctx.lineWidth = 10;
ctx.stroke();
if(end >= 360) {
clearInterval(int);
}
}, 10);
ctx.beginPath();
ctx.arc(220, 80, 50, degreesToRadians(0)-Math.PI/2, degreesToRadians(360)-Math.PI/2, false);
ctx.lineWidth = 10;
ctx.stroke();
(raw simple code, dont mind the sloppiness)
You need a:
ctx.clearRect(0, 0, w, h);
In each draw loop.
Basically, you are drawing the same arc over itself hundreds of times. The edge pixels that are only partially black are bing darkened over and over until they are completely black.
Things like this are way nearly all canvas animations clear the canvas and draw fresh for each iteration.
Try clearing the drawing rectangle on every frame
ctx.clearRect(x,y,width,height);
http://jsfiddle.net/C8CXz/3/
I found that I first need the clear the canvas.
ctx.clearRect(0, 0, canvas.width, canvas.height);

Categories

Resources