Drawing lights on a canvas - javascript

Hi i'm trying to draw lights in a canvas like this:
<canvas id="myCanvas" width="600" height="300"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "rgba(0,0,0,0.75)";
ctx.fillRect(0,0,300,300);
ctx.clearRect(0,0,300,300);
var grd = ctx.createRadialGradient(150,150,0,150,150,150);
grd.addColorStop(0, "rgba(255,255,0,0)");
grd.addColorStop(1, "rgba(0,0,0,0.75)");
ctx.fillStyle = grd;
ctx.fillRect(0,0,300,300);
ctx.clearRect(300,0,600,300);
var grd = ctx.createRadialGradient(450,150,0,450,150,150);
grd.addColorStop(0, "rgba(255,255,0,0)");
grd.addColorStop(1, "rgba(0,0,0,0.75)");
ctx.fillStyle = grd;
ctx.fillRect(300,0,600,300);
</script>
The problem is when the lights overlap
<canvas id="myCanvas" width="500" height="300"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "rgba(0,0,0,0.75)";
ctx.fillRect(0,0,300,300);
ctx.clearRect(0,0,300,300);
var grd = ctx.createRadialGradient(150,150,0,150,150,150);
grd.addColorStop(0, "rgba(255,255,0,0)");
grd.addColorStop(1, "rgba(0,0,0,0.75)");
ctx.fillStyle = grd;
ctx.fillRect(0,0,300,300);
ctx.clearRect(200,0,500,300);
var grd = ctx.createRadialGradient(350,150,0,350,150,150);
grd.addColorStop(0, "rgba(255,255,0,0)");
grd.addColorStop(1, "rgba(0,0,0,0.75)");
ctx.fillStyle = grd;
ctx.fillRect(200,0,500,300);
</script>
I need the lights come together and not overlap
also i need to see an image below the canvas
how can i Solve ?
that's the effect i'm looking for
I've used 2 canvas, 1 for scenery and 1 above for lights
This is almost what i'm looking for , but it remains a bit 'darker where the lights overlap, there is too little light in the center of each light, and it looks like a white light instead of a yellow light
http://jsfiddle.net/vgmc4m87/
Thanks

If you really want to overlap those two gradients, I would suggest a few things,
Get rid of the clearRect()
Change
grd.addColorStop(0, "rgba(255,255,0,0)"); grd.addColorStop(1, "rgba(0,0,0,0.75)");
Such that the second color stop has 0 alpha component, this way the gradient will actually fade out as it goes towards the edge of the circle. And you can actually overlap circles only if they're fading towards the end.
Don't use fillRect(), use arcs instead.
See, https://jsfiddle.net/fL4xffnq/3/. I've not preserved colours, but it should give you a good idea on how to proceed.

jsFiddle : https://jsfiddle.net/CanvasCode/p3k7cwqs/
javascript
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext("2d");
var image = new Image();
image.src = "http://images4.fanpop.com/image/photos/16000000/Beautiful-Cat-cats-16096437-1280-800.jpg";
image.onload = function () {
ctx.drawImage(image, 0, 0, 500, 400);
var grd = ctx.createRadialGradient(150, 150, 0, 0, 150, 200);
grd.addColorStop(0, "rgba(255,255,0,1)");
grd.addColorStop(1, "rgba(0,0,0,0)");
ctx.beginPath();
ctx.fillStyle = grd;
ctx.arc(150, 150, 200, 0, Math.PI * 2, false)
ctx.fill();
var grd = ctx.createRadialGradient(350, 150, 0, 350, 150, 200);
grd.addColorStop(0, "rgba(255,255,0,1)");
grd.addColorStop(1, "rgba(0,0,0,0)");
ctx.beginPath();
ctx.fillStyle = grd;
ctx.arc(350, 150, 200, 0, Math.PI * 2, false)
ctx.fill();
};

Adding to #nisargjhaveri's answer setting ctx.globalCompositeOperation = "lighter" creates a nice effect.
function drawBackground() {
var can = document.getElementById('background');
var ctx = can.getContext('2d');
var grd = ctx.createLinearGradient(0, 0, 0, 150);
grd.addColorStop(0, "rgba(0,255,255,1)");
grd.addColorStop(1, "rgba(30,100,200,1)");
ctx.fillStyle = grd;
ctx.fillRect(0, 0, 500, 150);
var grd = ctx.createLinearGradient(0, 150, 0, 300);
grd.addColorStop(0, "rgba(15,75,25,1)");
grd.addColorStop(1, "rgba(30,150,50,1)");
ctx.fillStyle = grd;
ctx.fillRect(0, 150, 500, 300);
}
drawBackground();
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var bg = document.getElementById("background");
var x1 = 150;
var y1 = 150;
var x2 = 350;
var y2 = 150;
var step1 = {
x: 1,
y: 1
};
var step2 = {
x: -1,
y: 1
};
function loop() {
ctx.save();
ctx.fillStyle = "rgba(0,0,0,1)";
ctx.clearRect(0, 0, 500, 300);
// Create a white to transparent gradient for the circles
// Circle one
var grd = ctx.createRadialGradient(x1, y1, 0, x1, y1, 150);
grd.addColorStop(.75, "rgba(255,255,0,1)");
grd.addColorStop(1, "rgba(255,255,0,0)");
ctx.beginPath();
ctx.fillStyle = grd;
ctx.arc(x1, y1, 150, 0, Math.PI * 2, false)
ctx.fill();
// Circle two
var grd = ctx.createRadialGradient(x2, y2, 0, x2, y2, 150);
grd.addColorStop(.75, "rgba(255,255,255,1)");
grd.addColorStop(1, "rgba(255,255,255,0)");
ctx.beginPath();
ctx.fillStyle = grd;
ctx.arc(x2, y2, 150, 0, Math.PI * 2, false)
ctx.fill();
// Fill the white part with the background image.
ctx.globalCompositeOperation = "source-atop";
ctx.drawImage(bg, 0, 0, bg.width, bg.height);
// Fill the transparent part with gray.
ctx.globalCompositeOperation = "destination-atop"
ctx.fillStyle = "rgba(63,63,63,1)";
ctx.fillRect(0, 0, c.width, c.height);
// clear the globalCompositeOperation
ctx.restore();
step1.x = x1 > c.width ? -1 : x1 < 0 ? 1 : step1.x;
step1.y = y1 > c.height ? -1 : y1 < 0 ? 1 : step1.y;
step2.x = x2 > c.width ? -1 : x2 < 0 ? 1 : step2.x;
step2.y = y2 > c.height ? -1 : y2 < 0 ? 1 : step2.y;
x1 += step1.x;
y1 += step1.y;
x2 += step2.x;
y2 += step2.y;
setTimeout(loop, 1000 / 60);
}
loop()
<canvas id="background" width="500" height="300" style='display:none'></canvas>
<canvas id="myCanvas" width="500" height="300"></canvas>

Related

html5 canvas - how to use 'destination-out' to clear out the most recently drawn shape only?

Suppose I have drawn a green rectangle and then a blue rectangle over it. I want to draw a circular hole in the blue rectangle so that the green rectangle underneath is visible through the hole.
I have tried using destination-out but it clears all shapes underneath:
const ctx = document.querySelector("#canvas").getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(0, 0, 50, 100);
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, 50, 50);
ctx.globalCompositeOperation = "destination-out";
ctx.beginPath();
ctx.arc(50 / 2 - 10 / 2, 50 / 2, 10, 0, Math.PI * 2);
ctx.fill();
ctx.globalCompositeOperation = "source-over";
<canvas
id="canvas"
width="500"
height="200"
style="background: black"
></canvas>
Create second canvas, add your blue rectangle to it, cut out circle and than merge it into first canvas:
const ctx = document.querySelector("#canvas").getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(0, 0, 50, 100);
const canvasTemp = document.createElement("canvas");
const ctxTemp = canvasTemp.getContext("2d");
ctxTemp.fillStyle = "blue";
ctxTemp.fillRect(0, 0, 50, 50);
ctxTemp.globalCompositeOperation = "destination-out";
ctxTemp.beginPath();
ctxTemp.arc(50 / 2 - 10 / 2, 50 / 2, 10, 0, Math.PI * 2);
ctxTemp.fill();
ctxTemp.globalCompositeOperation = "source-over";
ctx.drawImage(canvasTemp, 0, 0);
<canvas
id="canvas"
width="500"
height="200"
style="background: black"
></canvas>
To draw behind the current content use the destination-over composite mode:
const ctx = document.querySelector("#canvas").getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, 50, 50);
ctx.globalCompositeOperation = "destination-out";
ctx.beginPath();
ctx.arc(50 / 2 - 10 / 2, 50 / 2, 10, 0, Math.PI * 2);
ctx.fill();
ctx.globalCompositeOperation = "destination-over";
ctx.fillStyle = "green";
ctx.fillRect(0, 0, 50, 100);
<canvas
id="canvas"
width="500"
height="200"
style="background: black"
></canvas>

How to convert an Arc into a Line with HTML5 Canvas?

I would like to animate a circle into a line with the radius equaling the width, and I am wondering how I can do this with an Arc? Or perhaps there is a better way?
From
To
Here's my arc:
function drawStar(x,y,size,scale,opacity,ctx){
ctx.save();
ctx.beginPath();
ctx.arc(x,y,size+scale,0,size+scale * Math.PI,false);
ctx.globalAlpha = opacity
ctx.closePath();
setFillStyle('rgb(255,237,219)',ctx);
ctx.fill()
ctx.restore();
}
I tried using ctx.scale(n,1), however it does not keep the same radius(width) and it scales the collection of arcs as a whole (zoom in effect).
Use instead a wide line-width value with "round" lineCap and stroke():
var ctx = c.getContext("2d");
ctx.lineWidth = 50;
ctx.lineCap = "round";
ctx.moveTo(45 , 25);
ctx.lineTo(45.5, 25); // in IE11 this must be slightly offset
ctx.moveTo( 45, 100);
ctx.lineTo(150, 100);
ctx.stroke();
<canvas id=c></canvas>
Remember beginPath() for animation.
You can use Bezier Curves to 'transform' your arc.
There's some math involved in calculating the perfect ends of your stretched circle but I guessed and tweaked my numbers.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(40, 20);
ctx.lineTo(100, 20);
ctx.bezierCurveTo(130, 20, 130, 60, 100, 60);
ctx.lineTo(40, 60);
ctx.bezierCurveTo(10, 60, 10, 20, 40, 20);
ctx.stroke();
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.moveTo(40, 80);
ctx.bezierCurveTo(68, 80, 68, 120, 40, 120);
ctx.bezierCurveTo(12, 120, 12, 80, 40, 80);
ctx.fill();
ctx.stroke();
<canvas id="myCanvas"></canvas>
You could draw the left and right halves of a circle using arc, then do a fillRect in between to connect them.
Edit: To elaborate on what I said earlier:
function init() {
let canvas = document.getElementById('myCanvas');
canvas.width = 400;
canvas.height = 400;
canvas.style.width = "400px";
canvas.style.height = "400px";
let ctx = canvas.getContext("2d");
function fillArc(ctx, cx, cy, r, startDeg, endDeg) {
ctx.beginPath();
ctx.arc(cx, cy, r, startDeg * Math.PI / 180, endDeg * Math.PI / 180);
ctx.fill();
}
function fillOval(ctx, cx, cy, r, sideLength, skipFirstArc) {
if (!skipFirstArc) {
fillArc(ctx, cx, cy, r, 90, 270);
}
ctx.fillRect(cx, cy - r, sideLength, r * 2);
fillArc(ctx, cx + sideLength, cy, r, 270, 90);
}
let sideLength = 0;
ctx.fillStyle = 'red';
function animateOval() {
if (sideLength === 100) {
ctx.clearRect(0, 0, 400, 400);
}
else {
fillOval(ctx, 30, 30, 25, sideLength, sideLength > 0);
}
++sideLength;
if (sideLength > 100) {
sideLength = 0;
}
}
setInterval(animateOval, 16);
}
Here's a Plunker with the above code running: http://plnkr.co/edit/vNqoUjPKg2lqC7JtYuEb?p=preview

How do I make something Rotate towards mouse?

I am trying to solve a question which has been bugging me for a while, can someone explain to me how to make the *red rectangle face/aim towards my mouse and explain to me how it works it would be awesome!!!
Here is the Fiddle
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var player = {
x: 200,
y: 200,
}
drawPlayer = function(something) {
context.beginPath();
context.fillStyle = "blue";
context.arc(something.x, something.y, 30, 0, 2 * Math.PI);
context.fill();
context.fillStyle = "red";
context.fillRect(something.x, something.y - 10, 50, 20);
context.restore();
}
update = function() {
context.clearRect(0, 0, 500, 500)
drawPlayer(player);
}
setInterval(update, 20);
<canvas id="canvas" style="outline: 1px solid #ccc" width="500" height="500"></canvas>
Use context.translate to translate coordinates to the center of your player and then context.rotate to rotate the rectangle.
To find the angle between the mouse position and the center of the player you can use Math.atan2 function.
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var player = {
x: 200,
y: 200,
}
drawPlayer = function(something, angle) {
context.clearRect(0, 0, 500, 500);
context.beginPath();
context.fillStyle = "blue";
context.arc(something.x, something.y, 30, 0, 2 * Math.PI);
context.fill();
// save the untranslated context
context.save();
context.beginPath();
// move the rotation point to the center of the player
context.translate(something.x, something.y);
context.rotate(angle);
context.fillStyle = "red";
// note that coordinates are translated,
// so 0 is player.x and -10 is player.y - 10
context.fillRect(0, - 10, 50, 20);
// restore the context to its untranslated state
context.restore();
}
drawPlayer(player, 0);
document.onmousemove = function(e) {
var angle = Math.atan2(e.pageY - player.y, e.pageX - player.x)
drawPlayer(player, angle);
}
<canvas id="canvas" style="outline: 1px solid #ccc" width="500" height="500"></canvas>

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.

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>

Categories

Resources