Draw overlap of 3 circles on a canvas - javascript

I need to draw the following image on an HTML5 canvas without a temporary canvas:
With a temporary canvas it's easy, because I can handle the overlaps independently like you can see here:
Check this jsFiddle.
// init
var canvas = document.getElementById('canvas');
var tempCanvas = document.getElementById('tempCanvas');
var ctx = canvas.getContext('2d');
var tempCtx = tempCanvas.getContext('2d');
// draw circle function
var drawCircle = function( c, color ) {
ctx.beginPath();
ctx.arc( c.x, c.y, 50, 0, 2 * Math.PI, false );
ctx.fillStyle = color;
ctx.fill();
}
// draw overlap function
var drawOverlap = function( c1, c2, color ) {
tempCtx.clearRect( 0, 0, 300, 300 );
// first circle
tempCtx.globalCompositeOperation = 'source-over';
tempCtx.beginPath();
tempCtx.arc( c1.x, c1.y, 50, 0, 2 * Math.PI, false );
tempCtx.fillStyle = color;
tempCtx.fill();
// second circle
tempCtx.globalCompositeOperation = 'destination-in';
tempCtx.beginPath();
tempCtx.arc( c2.x, c2.y, 50, 0, 2 * Math.PI, false );
tempCtx.fill();
// draw on main canvas
ctx.drawImage( tempCanvas, 0, 0 );
}
// circle objects
var c1 = { x:100, y: 200 };
var c2 = { x:180, y: 200 };
var c3 = { x:140, y: 140 };
// draw background
ctx.beginPath();
ctx.rect( 0, 0, 300, 300 );
ctx.fillStyle = 'black';
ctx.fill();
// draw circles
drawCircle( c1, 'grey' );
drawCircle( c2, 'white' );
drawCircle( c3, 'white' );
// draw overlaps
drawOverlap( c1, c2, 'red' );
drawOverlap( c1, c3, 'blue' );
drawOverlap( c2, c3, 'blue' );
Do you know a way to draw this without a second canvas? Thanks a lot.
EDIT:
I solved it thanks to #user13500. There are still ugly borders but it's very fast:
Check this jsFiddle

Ai, my head hurts.
Not a quite a solution. Not one at all I guess. But if we do not care about the background we have this:
Fiddle Updated to new version as below.
Giving us this:
Tried to solve this using only globalCompositeOperation ;-P
Edit:
OK. Moving away from it for a few minutes and here we go again. This time with this as result. There is still the issue with stray lines around the circle red:
Though it might not be what you are after, it is here ;-) #markE is in another realm when it comes to authority on the subject.
Fiddle.
Code:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var ct = [
'source-over', // 0
'source-in', // 1
'source-out', // 2
'source-atop', // 3
'destination-over', // 4
'destination-in', // 5
'destination-out', // 6
'destination-atop', // 7
'lighter', // 8
'darker', // 9
'copy', // 10
'xor' // 11
];
ctx.beginPath();
ctx.globalCompositeOperation = ct[0];
ctx.fillStyle = "#888";
ctx.arc(100,200,50,0,2*Math.PI);
ctx.fill();
ctx.beginPath();
ctx.globalCompositeOperation = ct[6];
ctx.fillStyle = "#fff";
ctx.arc(180,200,50,0,2*Math.PI);
ctx.fill();
ctx.beginPath();
ctx.globalCompositeOperation = ct[11];
ctx.fillStyle = "#f00";
ctx.arc(100,200,50,0,2*Math.PI);
ctx.fill();
ctx.beginPath();
ctx.globalCompositeOperation = ct[4];
ctx.fillStyle = "#888";
ctx.arc(100,200,50,0,2*Math.PI);
ctx.fill();
ctx.beginPath();
ctx.globalCompositeOperation = ct[9];
ctx.fillStyle = "#fff";
ctx.arc(180,200,50,0,2*Math.PI);
ctx.fill();
ctx.beginPath();
ctx.globalCompositeOperation = ct[11];
ctx.fillStyle = "#fff";
ctx.arc(140,140,50,0,2*Math.PI);
ctx.fill();
ctx.beginPath();
ctx.globalCompositeOperation = ct[4];
ctx.fillStyle = "#00f";
ctx.arc(140,140,50,0,2*Math.PI);
ctx.fill();
ctx.beginPath();
ctx.globalCompositeOperation = ct[4];
ctx.rect( 0, 0, 300, 300 );
ctx.fillStyle = '#000';
ctx.fill();

You can do this without a temporary canvas using clipping regions -- context.clip()
If you need, I can code the solution but since you know how to do compositing you can probably figure it out quickly ;)
But more importantly! ...
Why are you disabling your tool choices by not using a temporary canvas?
You could do document.createElement("canvas") to create a temporary canvas that's not even visible on the screen.

Related

How to hide the path immediate overlap without hiding intersection overlap?

I'm making a painting app, and using the canvas path as a brush:
function onMove(){
ctx.beginPath();
ctx.moveTo(pos.x, pos.y); // from position
pos=getPosition(event);
ctx.lineTo(pos.x, pos.y); // to position
ctx.stroke(); // draw it!
}
I'm stuck between in a dilemma, if I join all the paths into one I lose intersection overlap, and if I draw them real time separately I get those start/end overlaps spheres.
Is there a clean way I can solve this problem? Thank you.
Okey, then it is getting complicated since we are dealing with alpha values here..
Basicly you can draw the "missing part" of the new line in a buffer canvas by using destination-in and source-in blend modes.
The idea is: to "compute" the overlapp of the N-1 the Nth line and then only draw line N outside this overlap:
(for demonstation the Nth line will be drawn in red.)
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const canvas2 = document.createElement('canvas')
canvas2.width = 300
canvas2.height = 300
const ctx2 = canvas2.getContext('2d');
ctx.lineWidth = 30
ctx.lineCap = 'round';
ctx.strokeStyle = 'rgba(0,0,0,0.5)';
ctx.imageSmoothingEnabled = false;
ctx.lineJoin = "round"
function drawLine1(ctx) {
ctx.beginPath();
ctx.moveTo(250, 250);
ctx.lineTo(100, 250);
ctx.stroke();
}
function drawLine2(ctx) {
ctx.beginPath();
ctx.moveTo(100, 250);
ctx.lineTo(100, 50);
ctx.stroke();
}
// draw image until line n-1 on screen
ctx.beginPath();
ctx.moveTo(0, 100);
ctx.lineTo(250, 100); // 1st
ctx.lineTo(250, 250); // 2nd
ctx.lineTo(100, 250); // n-1
ctx.stroke();
// clear buffer canvas and setup
ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
ctx2.lineWidth = 30
ctx2.lineCap = 'round';
ctx2.imageSmoothingEnabled = false;
// draw line n-1 on buffer in opaque color
ctx2.strokeStyle = 'rgba(0,0,0,1)';
drawLine1(ctx2)
// draw line n on buffer in "destination-in" blend mode opaque
ctx2.globalCompositeOperation = 'destination-in';
ctx2.strokeStyle = 'rgba(0,0,0,1)';
drawLine2(ctx2)
// draw line n on buffer in "source-out" blend mode and original color
ctx2.globalCompositeOperation = 'source-out';
ctx2.strokeStyle = 'rgba(255,0,0,0.5)';
drawLine2(ctx2)
ctx.drawImage(canvas2, 0 ,0)
<canvas id="canvas" width="400" height="400"></canvas>
It is not perfect, but it is a starting point..

How can I move just one of many shapes inside canvas by 50 pixels;

I have a project to do and I cannot do it until I understand how moving object inside canvas work.
I need to move one of the objects below by 50pixels to right.
Anyone willing to help me is greatly appreciated.
Meanwhile thank you very much in advance for your help or suggestions.
function canvasOneShape() {
//refers to the html canvasone id
var canvas = document.getElementById("canvasOne");
this.canvasOne.width = 945;
this.canvasOne.height = 650;
// draws the canvas in 2d
var ctx = canvas.getContext("2d");
// Set the fill colour to blue.
ctx.fillStyle = "blue"; //used like this instead of rgb due personal preference:)
// Create a filled rectangle at co-ordinates (10,10)
// with height and width set to 100.
ctx.fillRect(10, 10, 250, 330); //
// Here I draw the square
// Set the canvas up for drawing in 2D.
// Set the fill colour to blue.
ctx.fillStyle = "rgba(244, 244, 189,.5)";
ctx.fillRect(10, 50, 330, 250);
//draw my first circle
var midXone = canvas.width / 2; //x location
var midXtwo = canvas.height / 2; //y location
var radius = 60; //circle radius
ctx.beginPath();
ctx.arc(midXone, midXtwo, radius, 0, 2 * Math.PI, false);
ctx.fillStyle ="rgba(89, 192, 227,.4)";
ctx.fill();
ctx.lineWidth = 5;
ctx.strokeStyle = '#003300';
ctx.stroke();
//draw the second circle
var midX = canvas.width / 2.35; //x location
var midY = canvas.height / 2.35; //y location
var radius = 50; //circle radius
ctx.beginPath();
ctx.arc(midX, midY, radius, 0, 2 * Math.PI, false);
ctx.fillStyle ="rgba(66, 244, 89,.4)";
ctx.fill();
ctx.lineWidth = 5;
ctx.strokeStyle ="rgba(255, 244, 9,.4)";
ctx.stroke();
//draw Square with circle inside
//square
ctx.fillStyle = "rgb(222, 33, 51)";
ctx.fillRect(550, 20, 300, 300);
//circle
ctx.beginPath();
ctx.arc(700, 170, 150, 0, 2 * Math.PI, false);
ctx.fillStyle ="rgba(66, 244, 89,.4)";
ctx.fill();
ctx.lineWidth = 1;
ctx.strokeStyle = '#f44242';
ctx.stroke();
//The Pacman object
var radius = 100; //circle radius
var x = 100;
var y = 500;
ctx.beginPath();
ctx.arc(120, 500, radius, 1.85 * Math.PI, .15 * Math.PI, true);
//Draw mouth
ctx.lineTo(120, 500);
ctx.closePath();
ctx.fillStyle = "rgb(255, 255, 0)";
ctx.fill();
ctx.lineWidth = 5;
ctx.strokeStyle = 'rgb(0,0,0)';
ctx.stroke();
//draw eye
ctx.beginPath();
ctx.arc(x + 40, y - 40, 10, 0 * Math.PI, 2 * Math.PI, true);
ctx.fillStyle = "rgb(0,0,0)";
ctx.fill();
}
there are no layers or objects on a canvas(it's just a single layer of pixels), so, if you draw something, you overwrite what's underneath it. to move something to the right, you will need to have a function to draw everything behind it, and then variables to store the location (x and y) of the objects you want to move.
then, to move it, you clear the canvas with
ctx.clearRect(0, 0,width of canvas, height height of canvas);,
call the background function to draw everything behind it again, and the redraw your object in a different location.

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>

HTML 5 Canvas, rotate everything

I made a cylinder gauge, very similar to this one:
It is drawn using about 7 or so functions... mine is a little different. It is very fleixble in that I can set the colors, transparency, height, width, whether there is % text shown and a host of other options. But now I have a need for the same thing, but all rotated 90 deg so that I can set the height long and the width low to generate something more like this:
I found ctx.rotate, but no mater where it goes all the shapes fall apart.. ctx.save/restore appears to do nothing, I tried putting that in each shape drawing function. I tried modifying, for example, the drawOval function so that it would first rotate the canvas if horizontal was set to one; but it appeared to rotate it every single iteration, even with save/restore... so the top cylinder would rotate and the bottom would rotate twice or something. Very tough to tell what is really happening. What am I doing wrong? I don't want to duplicate all this code and spend hours customizing it, just to produce something I already have but turned horizontal. Erg! Help.
Option 1
To rotate everything just apply a transform to the element itself:
canvas.style.transform = "rotate(90deg)"; // or -90 depending on need
canvas.style.webkitTransform = "rotate(90deg)";
Option 2
Rotate context before drawing anything and before using any save(). Unlike the CSS version you will first need to translate to center, then rotate, and finally translate back.
You will need to make sure width and height of canvas is swapped before this is performed.
ctx.translate(ctx.canvas.width * 0.5, ctx.canvas.height * 0.5); // center
ctx.rotate(Math.PI * 0.5); // 90°
ctx.translate(-ctx.canvas.width * 0.5, -ctx.canvas.height * 0.5);
And of course, as an option 3, you can recalculate all your values to go along the other axis.
Look at the rotate function in this example. You want to do a translation to the point you want to rotate around.
example1();
example2();
function rotate(ctx, degrees, x, y, fn) {
ctx.save();
ctx.translate(x, y);
ctx.rotate(degrees * (Math.PI / 180));
fn();
ctx.restore();
}
function rad(deg) {
return deg * (Math.PI / 180);
}
function example2() {
var can = document.getElementById("can2");
var ctx = can.getContext('2d');
var w = can.width;
var h = can.height;
function drawBattery() {
var percent = 60;
ctx.beginPath();
ctx.arc(35,50, 25,0,rad(360));
ctx.moveTo(35+percent+25,50);
ctx.arc(35+percent,50,25,0,rad(360));
ctx.stroke();
ctx.beginPath();
ctx.fillStyle = "rgba(0,255,0,.5)";
ctx.arc(35,50,25,0,rad(360));
ctx.arc(35+percent,50,25,0,rad(360));
ctx.rect(35,25,percent,50);
ctx.fill();
ctx.beginPath();
ctx.lineWidth = 2;
ctx.strokeStyle = "#666666";
ctx.moveTo(135,25);
ctx.arc(135,50,25, rad(270), rad(269.9999));
//ctx.moveTo(35,75);
ctx.arc(35,50,25,rad(270),rad(90), true);
ctx.lineTo(135,75);
ctx.stroke();
}
drawBattery();
can = document.getElementById("can3");
ctx = can.getContext('2d');
w = can.width;
h = can.height;
rotate(ctx, -90, 0, h, drawBattery);
}
function example1() {
var can = document.getElementById('can');
var ctx = can.getContext('2d');
var color1 = "#FFFFFF";
var color2 = "#FFFF00";
var color3 = "rgba(0,155,255,.5)"
var text = 0;
function fillBox() {
ctx.save();
ctx.fillStyle = color3;
ctx.fillRect(0, 0, can.width / 2, can.height);
ctx.restore();
}
function drawBox() {
ctx.save();
ctx.beginPath();
ctx.strokeStyle = ctx.fillStyle = color1;
ctx.rect(10, 10, 50, 180);
ctx.font = "30px Arial";
ctx.fillText(text, 25, 45);
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle = color2;
ctx.lineWidth = 10;
ctx.moveTo(10, 10);
ctx.lineTo(60, 10);
ctx.stroke();
ctx.restore();
}
fillBox();
rotate(ctx, 90, can.width, 0, fillBox);
text = "A";
drawBox();
color1 = "#00FFFF";
color2 = "#FF00FF";
text = "B";
rotate(ctx, 90, can.width, 0, drawBox);
centerRotatedBox()
function centerRotatedBox() {
ctx.translate(can.width / 2, can.height / 2);
for (var i = 0; i <= 90; i += 10) {
var radians = i * (Math.PI / 180);
ctx.save();
ctx.rotate(radians);
ctx.beginPath();
ctx.strokeStyle = "#333333";
ctx.rect(0, 0, 50, 50)
ctx.stroke();
ctx.restore();
}
}
}
#can,
#can2,
#can3 {
border: 1px solid #333333
}
<canvas id="can" width="200" height="200"></canvas>
<canvas id="can2" width="200" height="100"></canvas>
<canvas id="can3" width="100" height="200"></canvas>

drawing canvas works as long i use it one time

I am drawing a canvas and rotating it based on a value, it works if i use the canvas one time on a page.
If i add it the second time to the page, only the last one gets drawn, i cant find the error in my code and i dont get a js error.
i think the problem is in the next function:
function animate(){
function drawnumbers()
{context.save();
context.fillStyle = "#000000";
context.translate(73,0);
context.font="10px Orbitron";
context.textAlign = "center";
context.rotate(((i*(180/min)))*Math.PI/180);
context.fillText(data.values[i].amount,0,3);
context.restore();
};
if (d < defer){
context.clearRect(0,0,400,400);
d++;
context.save();
var ang = ((((d-minn)*(180/angle)))*(Math.PI/180));
context.translate(38,39);
context.scale(.8,.8);
base_image = new Image();
base_image.src = 'http://oi44.tinypic.com/2hfkx8p.jpg';
context.translate(base_image.width/2, base_image.height/2);
context.rotate(ang );
context.drawImage(base_image, -base_image.width/2, -base_image.height/2);
context.restore();
context.save();
context.beginPath();
context.arc(100,100,64,1*Math.PI,2*Math.PI, false);
context.lineWidth = .4;
context.strokeStyle="#00A1DE";
context.globalAlpha = 0.7;
context.stroke();
context.restore();
context.save();
context.translate(100,100);
context.rotate(Math.PI/180);
context.strokeStyle = "#00A1DE";
context.lineWidth = .7;
for (var i=0;i < data.values.length; i++){
context.beginPath();
context.moveTo(62,0);
context.lineTo(67,0);
context.stroke();
context.globalAlpha = 0.7;
drawnumbers();
context.rotate((182/(min))*(-Math.PI/180));
}
context.restore();
context.fillStyle="white";
context.fillRect(38,101,123,75);
context.save();
context.fillStyle = "#00a1de";
context.font = "22px Orbitron";
context.textAlign = "center";
context.fillText(defer, 100, 90);
context.restore();
context.save();
context.fillStyle = "#000000";
context.font = "10px arial";
context.textAlign = "center";
context.fillText(eenheid, 100, 115);
context.restore();
}
else
{
clearTimeout(t);
};
t=setTimeout("animate()",30-d);
};
check example to better understand:
http://jsbin.com/ogEgURu/1/
I had it in a function but it remains the same problem so i think something is wrong with my code.
Can anyone see the problem i am not seeing ?
Your code is way too complex, especially since there is no good reason for this complexity.
Copying a big (>200) lines block of code to duplicate a functionality is error-prone.
You'll be able to see easily the issue once you refactored your code.
Just a few hints :
Very easy one : beautify the code.
No redundancy : If a code lies here twice or more, make a function and factorize.
Break down the code into smaller parts. For example : drawText(context, text, x,y, font ) (to print eenheid and defer), drawNumbers(context), drawRotatingImage(context, angle), ...
use closePath() each time you beginPath();
load once the image when page loads, and wait for it to be loaded before animating.
do not define a function in a loop (drawnumbers).
use a single object to store the several parameters (context, angle, ...), or
even switch to an object oriented style.
have only one animate() loop, that will call several draw(...) functions if need be.
after all this, your code will look much simpler, and the bug should vanish very quickly.
I did this work (partially), in this fiddle :
http://jsfiddle.net/gamealchemist/ztczK/1/ (edited)
The code looks like :
// parameters : settings for one gauge display
var parameters1 = {
data: data,
defer: '520',
context: context,
left: 38,
top: 30,
d: 0,
angle: 0,
scale: 0.8,
//... whatever parameter here
};
var parameters2 = ... ;
split the draw into many functions so it's much simpler to understand :
// draws a gauge
function drawGauge(param) {
preDraw(param);
drawBaseImage(param);
drawArc(param);
drawTheNumbers(param);
writeDefer(param);
writeEenheid(param);
postDraw(param);
}
// translate and scales context, and updates some values for the gauge
function preDraw(param) {
var minn = param.data.values[param.data.values.length - 1].amount;
var maxn = data.values[0].amount;
var angle = maxn - minn;
var d = param.d;
param.ang = ((((d - minn) * (180 / angle))) * (Math.PI / 180));
var ctx = param.context;
ctx.save();
ctx.translate(param.left, param.top);
ctx.scale(param.scale, param.scale);
context.fillStyle = "white";
context.fillRect(0, 60, 123, 75);
}
// restore context
function postDraw(param) {
var ctx = param.context;
ctx.restore();
param.d++;
}
function drawBaseImage(param) {
var ctx = param.context;
var ang = param.ang;
ctx.save();
ctx.translate(base_image.width / 2, base_image.height / 2);
ctx.rotate(ang);
ctx.drawImage(base_image, -base_image.width / 2, -base_image.height / 2);
ctx.restore();
}
function drawArc(param) {
var ctx = param.context;
ctx.save();
ctx.beginPath();
ctx.arc(base_image.width / 2, base_image.height / 2, 64, 1 * Math.PI, 2 * Math.PI, false);
ctx.lineWidth = .4;
ctx.strokeStyle = "#00A1DE";
ctx.globalAlpha = 10.7;
ctx.stroke();
ctx.restore();
}
function writeDefer(param) {
var ctx = param.context;
var defer = param.defer;
ctx.save();
ctx.fillStyle = "#00a1de";
ctx.font = "22px Orbitron";
ctx.textAlign = "center";
ctx.fillText(defer, base_image.width / 2, base_image.height / 2);
ctx.restore();
}
function writeEenheid(param) {
var ctx = param.context;
ctx.save();
ctx.fillStyle = "#000000";
ctx.font = "10px arial";
ctx.textAlign = "center";
ctx.fillText(eenheid, base_image.width / 2, base_image.height / 2 + 20);
ctx.restore();
}
function drawTheNumbers(param) {
var ctx = param.context;
var dataValues = param.data.values;
var count = dataValues.length;
ctx.save();
ctx.translate(base_image.width / 2, base_image.height / 2);
ctx.rotate(Math.PI / 180);
ctx.strokeStyle = "#00A1DE";
ctx.lineWidth = .7;
ctx.fillStyle = "#000000";
ctx.font = "10px Orbitron";
ctx.textAlign = "center";
ctx.globalAlpha = 0.7;
for (var i = 0; i < count; i++) {
ctx.beginPath();
ctx.moveTo(62, 0);
ctx.lineTo(67, 0);
ctx.stroke();
ctx.closePath();
ctx.fillText(dataValues[i].amount, 60, 3);
ctx.rotate(-Math.PI / count);
}
context.restore();
}
then animate becomes very simple, even with several gauges :
function animate() {
context.clearRect(0, 0, canvasWidth, canvasHeight);
drawGauge(parameters1);
drawGauge(parameters2);
setTimeout(animate, 15);
};
base_image.onload = animate();

Categories

Resources