how to feather edges of image in html5 canvas or fabricjs - html5-canvas

<canvas id="canvas" width="300" height="300" style="background:green">
<img id="shape" onload="run()" src="shape.png">
<script>
function run()
{
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
const im = document.getElementById('shape');
context.drawImage(im, 0, 0);
}
</script>
how to get feathered edges around the white part of the image for my custom shape.
The green color in the image is transparent.
I tried with shadowblur but that is not what I want
I want to blur edges as if it is fading into background.
I want to do this using html5 canvas or using fabricjs.
Note : The shape is not circle or oval. It is a custom hand drawn shape.

You can draw your shape with a CSS blur() filter and then use that as a mask.
If you need to support Safari, which still doesn't support ctx.filter (and maybe will never...) you can actually do the same with shadows, the trick is to render the mask outside of the visible viewport and add a huge offset on the shadow.
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const mask = new Image();
// using #obscure's image
mask.src = "https://i.stack.imgur.com/tyKHb.png";
const img = new Image();
img.src = "https://picsum.photos/200/200";
Promise.all([
mask.decode(),
img.decode()
]).then(draw);
function draw() {
canvas.width = img.width;
canvas.height = img.height;
if (ctx.filter === "none") {
ctx.filter = "blur(5px)";
ctx.drawImage(mask, 0, 0);
ctx.filter = "none";
}
else { // thanks Safari
ctx.shadowOffsetX = 200;
ctx.shadowBlur = 5;
ctx.shadowColor = "black";
ctx.drawImage(mask, -200, 0);
}
ctx.globalCompositeOperation = "source-in";
ctx.drawImage(img, 0, 0);
}
<canvas></canvas>

There are quite a few steps involved to accomplish this task.
Say we have a hand-drawn shape like this:
First we need to get the outline of the actual shape. As it's a solid single coloured shape we can simply look for non-transparent pixels, or pixels that are above a certain threshold. Based on this data we need to get the contours that form the shape.
Luckily we don't need to re-invent the wheel as this is just what the d3 contours module does and we end up with something like this:
In the next step we need to determine the center point of the shape. This is done by looking through the points data returned in the last step and find the min/max horizontal and vertical values.
let rect = {
x1: Number.MAX_VALUE,
y1: Number.MAX_VALUE,
x2: Number.MIN_VALUE,
y2: Number.MIN_VALUE
};
for (let a = 0; a < points.length; a++) {
rect.x1 = points[a][0] < rect.x1 ? points[a][0] : rect.x1;
rect.y1 = points[a][1] < rect.y1 ? points[a][1] : rect.y1;
rect.x2 = points[a][0] > rect.x2 ? points[a][0] : rect.x2;
rect.y2 = points[a][1] > rect.y2 ? points[a][1] : rect.y2;
}
let center = {
x: (rect.x1 + rect.x2) / 2,
y: (rect.y1 + rect.y2) / 2
};
Finally we fill the inside of the shape and redraw the outlines, say 20 times. With each iteration we enlarge the shape by 1 pixel and reduce the alpha value of the stroke until hitting zero, which will give us:
Now it's just a matter of combining the mask with an image by setting the globalCompositeOperation to 'source-atop'.
Here's the complete example:
let image = new Image();
let mask = new Image();
let canvas = document.getElementById('canvas');
let context = canvas.getContext('2d');
let imagesLoaded = 0;
context.fillStyle = 'rgb(255,0,0)';
image.crossOrigin = 'anonymous';
mask.crossOrigin = 'anonymous';
image.onload = loaded;
mask.onload = loaded;
image.src = 'https://api.codetabs.com/v1/proxy?quest=https://picsum.photos/id/237/200/200';
mask.src = 'https://api.codetabs.com/v1/proxy?quest=https://i.stack.imgur.com/tyKHb.png';
function loaded() {
imagesLoaded++;
if (imagesLoaded == 2) {
process();
}
}
function process() {
context.drawImage(mask, 0, 0, image.width, image.height);
let imageData = context.getImageData(0, 0, canvas.width, canvas.height).data;
let points = d3.geom.contour((x, y) => {
let a = imageData[(y * canvas.width + x) * 4 + 3];
return (a > 0);
});
context.clearRect(0, 0, canvas.width, canvas.height);
let rect = {
x1: Number.MAX_VALUE,
y1: Number.MAX_VALUE,
x2: Number.MIN_VALUE,
y2: Number.MIN_VALUE
};
for (let a = 0; a < points.length; a++) {
rect.x1 = points[a][0] < rect.x1 ? points[a][0] : rect.x1;
rect.y1 = points[a][1] < rect.y1 ? points[a][1] : rect.y1;
rect.x2 = points[a][0] > rect.x2 ? points[a][0] : rect.x2;
rect.y2 = points[a][1] > rect.y2 ? points[a][1] : rect.y2;
}
let center = {
x: (rect.x1 + rect.x2) / 2,
y: (rect.y1 + rect.y2) / 2
};
let point = {};
for (let a = 0; a < 20; a++) {
context.strokeStyle = 'rgba(255,0,0,' + (1 - a / 20) + ')';
point.x = points[0][0];
point.y = points[0][1];
point.x = point.x < center.x ? point.x -= a : point.x += a;
point.y = point.y < center.y ? point.y -= a : point.y += a;
context.moveTo(point.x, point.y);
for (let b = 1; b < points.length; b++) {
point.x = points[b][0];
point.y = points[b][1];
point.x = point.x < center.x ? point.x -= a : point.x += a;
point.y = point.y < center.y ? point.y -= a : point.y += a;
context.lineTo(point.x, point.y);
}
context.closePath();
if (a == 0) {
context.fill();
}
context.stroke();
}
context.globalCompositeOperation = 'source-atop';
context.drawImage(image, 0, 0, canvas.width, canvas.height);
}
<script type="text/javascript">
let d3 = {
geom: {}
};
</script>
<script src="https://api.codetabs.com/v1/proxy?quest=https://raw.githubusercontent.com/d3/d3-plugins/master/geom/contour/contour.js"></script>
<canvas id="canvas" width="200" height="200"></canvas>

Related

cannot get collision detection on ball to floor array?

I can't seem to get collision detection to work with the floor array? I seem to be having the issue in the ballMovement function.
The ball falls straight through the rectangles made by the array.
Floor Array (issue)
Collision Detection
<html lang=en>
<head>
<meta charset=utf-8>
<title>Javascript gravity</title>
<link rel="stylesheet" href="game.css">
</head>
<body onload="init()">
<script>
var canvas, ctx, container;
canvas = document.createElement( 'canvas' );
ctx = canvas.getContext("2d");
var ball;
var message = "Helloworld";
// Velocity x
var vx = 2.0;
// Velocity y - randomly set
var vy;
var gravity = 0.5;
var bounce = 0.7;
var xFriction = 0.1;
// Floor Array
var floor = new Array();
//Rectagles
Rectangle = function(x, y, w, h, color){
if (x == null || y == null || w == null || h == null){
alert("You must pass in all the veriables for a rectange: (x, y, width, height)");
var errorMsg = "The following are not provided:";
if (x == null)
errorMsg += " 'x' ";
if (y == null)
errorMsg += " 'y' ";
if (w == null)
errorMsg += " 'width' ";
if (h == null)
errorMsg += " 'height'";
alert(errorMsg);
throw new Error(errorMsg);
}
this.x = x;
this.y = y;
this.width = w;
this.height = h;
this.color = new Color();
this.Contains = function(x, y){
if (x >= this.x && x <= this.x + this.width &&
y >= this.y && y <= this.y + this.height)
return true;
else
return false;
};
this.Draw = function(ctx){
ctx.fillStyle = this.color.ToStandard();
ctx.fillRect(this.x, this.y, this.width, this.height);
}
};
//Rectangle Colors
Color = function(r, g, b, a){
this.r = 255;
this.g = 255;
this.b = 255;
this.a = 1;
if (r != null)
this.r = r;
if (g != null)
this.g = g;
if (b != null)
this.b = b;
if (a != null)
this.a = a;
this.ToStandard = function(noAlpha){
if (noAlpha == null || !noAlpha)
return "rgba(" + this.r + "," + this.g + "," + this.b + "," + this.a + ")";
else
return "rgb(" + this.r + "," + this.g + "," + this.b + ")";
};
};
function init(){
setupCanvas();
vy = (Math.random() * -5) + -5;
ball = {x:canvas.width / 2, y:100, radius:10, status: 0, color:"red"};
floor.push(new Rectangle(0, 480, 500, 20));
floor.push(new Rectangle(250, 350, 200, 20));
//floor.push(new Rectangle(150, 300, 20, 20));
//floor.push(new Rectangle(200, 250, 20, 20));
//floor.push(new Rectangle(250, 200, 20, 20));
//floor.push(new Rectangle(300, 150, 20, 20));
//floor.push(new Rectangle(350, 100, 20, 20));
//floor.push(new Rectangle(400, 50, 20, 20));
for (var i = 0; i < floor.length; i++)floor[i].color = new Color(0, 0, 0, 1);
}//end init method
function draw() {
ctx.clearRect(0,0,canvas.width, canvas.height);
for (var i = 0; i < floor.length; i++)
floor[i].Draw(ctx);
//display some text
ctx.fillStyle = "red";
ctx.font = "20px Arial";
ctx.fillText(message, 20,20);
//draw cirlce
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI*2, false);
ctx.fillStyle = ball.color;
ctx.fill();
ctx.closePath();
ballMovement();
}
setInterval(draw, 1000/35);
function ballMovement(){
ball.x += vx;
ball.y += vy;
vy += gravity;
//If either wall is hit, change direction on x axis
if (ball.x + ball.radius > canvas.width || ball.x - ball.radius < 0){
vx *= -1;
}
// Ball hits the canvas floor
if (ball.y + ball.radius > canvas.height){// ||
// Re-positioning on the base
ball.y = canvas.height - ball.radius;
//bounce the ball
vy *= -bounce;
//do this otherwise, ball never stops bouncing
if(vy<0 && vy>-2.1)
vy=0;
//do this otherwise ball never stops on xaxis
if(Math.abs(vx)<1.1)
vx=0;
xF();
}
// Ball hits the rectangles
if (ball.y + ball.radius > floor.width){// ||
// Re-positioning on the base
ball.y = floor.height - ball.radius;
//bounce the ball
vy *= -bounce;
//do this otherwise, ball never stops bouncing
if(vy<0 && vy>-2.1)
vy=0;
//do this otherwise ball never stops on xaxis
if(Math.abs(vx)<1.1)
vx=0;
xF();
}
}
function xF(){
if(vx>0)
vx = vx - xFriction;
if(vx<0)
vx = vx + xFriction;
}
function setupCanvas() {//setup canvas
container = document.createElement( 'div' );
container.className = "container";
canvas.width = 500;
canvas.height = 500;
document.body.appendChild( container );
container.appendChild(canvas);
ctx.strokeStyle = "red";
ctx.lineWidth =1;
}
</script>
</body>
</html>
There are a couple of mistakes:
You compare the ball position on Y axis ball.y to the bar width floor.width, it may be a typing/editing mistake.
You should replace floor.width by floor.y to check whether the ball hits the bar when it falls.
But floor is an Array of Rectangle, it includes the bar and potential bricks to break, if I guess it right. So you need to loop through floor before checking, otherwise floor.height equals undefined.
for (let i = 0; i < floor.length; i += 1) {
const rect = floor[i];
// Ball hits the rectangle
if (ball.y + ball.radius > rect.y) {
// ...
}
}
Then, floor isn't an appropriate name for an Array which doesn't contain any 'floor'.
Finally, add a condition to handle the ball X position (collisions with the bar, the bricks, etc.).
Working example:
https://jsfiddle.net/nmerinian/3sokr512/22/
Have a good day

HTML5 Canvas - Add border to transparent png with drop shadow

There are two issues I'm trying to hammer through still in this canvas script to get this image the way I want it to look. The green is just for demo. Eventually it will be white with a gray drop shadow.
1) I want to add a gray drop shadow to the image after it gets it's green border.
2) I want the corners of the green border to be square, not rounded.
var c = document.getElementById("canvas"),
ctx = c.getContext("2d"),
opaqueAlpha = 255,
img = new Image();
img.onload = function(){
ctx.shadowColor = '#0f0'; // green for demo purposes
ctx.shadowBlur = 20;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
ctx.drawImage(img, 30, 30);
img = ctx.getImageData(0, 0, ctx.canvas.width - 1, ctx.canvas.height - 1);
// turn all non-transparent pixels to full opacity
for (var i = img.data.length; i > 0; i -= 4) {
if (img.data[i+3] > 0) {
img.data[i+3] = opaqueAlpha;
}
}
// write transformed opaque pixels back to image
ctx.putImageData(img, 0, 0);
// trying to get the img again and then apply the gray drop shadow...not working
img = ctx.getImageData(0, 0, ctx.canvas.width - 1, ctx.canvas.height - 1);
// need to add a gray shadow to the now opaque border
ctx.shadowColor = '#aaa';
ctx.shadowBlur = 10;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
ctx.putImageData(img, 0, 0);
};
img.setAttribute('crossOrigin', '');
img.src = "https://i.ezr.io/racks/bb0e6dd421df72541a79f271fb4f1a90.png?" + new Date().getTime();
<canvas id="canvas" width="800" height="800"></canvas>
This is how I would do it:
I know the width and the height of the image (img.width, img.height)
Also I know the offset: 30. You begin to draw the image at 30 units from the origin.
Since those distinctions are looking more or less the same I need to calculate 3 points to know how to draw the upper notches.
I hope this is what you need:
var c = document.getElementById("canvas"),
cw = (canvas.width = 750),
ch = (canvas.height = 310),
ctx = c.getContext("2d"),
opaqueAlpha = 255,
img = new Image();
img.onload = function() {
let offset = 30;
let whiteBorder = 15;
ctx.drawImage(img, offset, offset);
var imgData = ctx.getImageData(0, 0, cw, ch);
var pixels = imgData.data;
//get some points
let y = offset + 5;
let index = y * imgData.width * 4;
let x1;
for (let i = 0; i < imgData.width * 4; i += 4) {
if (pixels[index + i + 3] > 0) {
//console.log(i / 4);
x1 = i / 4;
break;
}
}
let x2;
for (let i = imgData.width * 4; i > 0; i -= 4) {
if (pixels[index + i] > 0) {
//console.log(i / 4);
x2 = i / 4;
break;
}
}
let x = (offset + 5) * 4;
let y1;
for (let i = 0; i < imgData.height; i++) {
if (pixels[i * imgData.width * 4 + x] > 0) {
//console.log(i);
y1 = i;
break;
}
}
// draw the border behind the image
ctx.globalCompositeOperation='destination-over';
ctx.beginPath();
ctx.moveTo(offset, img.height + offset);
ctx.lineTo(img.width + offset, img.height + offset);
ctx.lineTo(img.width + offset, y1);
ctx.lineTo(x2, y1);
ctx.lineTo(x2, offset);
ctx.lineTo(x1, offset);
ctx.lineTo(x1, y1);
ctx.lineTo(offset, y1);
ctx.closePath();
ctx.strokeStyle = "white";
ctx.lineWidth = 25;
ctx.stroke();
};
img.setAttribute("crossOrigin", "");
img.src =
"https://i.ezr.io/racks/bb0e6dd421df72541a79f271fb4f1a90.png?" +
new Date().getTime();
canvas{
filter:drop-shadow(0px 0px 5px #333);
}
<canvas id="canvas"></canvas>

Key down event to change background canvas

So I'm trying to have the down arrow make the background of my canvas change. I'm having trouble just getting the button press to work itself.
Also I was told that I would have to have a function redraw all the shapes that are already there at the beginning as well, which I am also stuck on what to change.
Here is a JSFiddle of what I have going so far, any suggestions are appreciated!
https://jsfiddle.net/u8avnky2/
var mainCanvas = document.getElementById("canvas");
var mainContext = mainCanvas.getContext('2d');
//rotate canvas
function buttonClick() {
mainContext.rotate(20*Math.PI/180);
}
//key down event
window.addEventListener('keydown', function(event) {
if (event.keyCode === 40) {
fillBackgroundColor();
}
});
function fillBackgroundColor() {
var colors = ["red", "green", "blue", "orange", "purple", "yellow"];
var color = colors[Math.floor(Math.random()*colors.length)];
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
mainContext.fillStyle = color;
mainContext.fillRect(0, 0, canvas.width, canvas.height);
}
function check() {
mainContext.clearRect(square.x,square.y,square.w,square.h);
}
var circles = new Array();
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
function Circle(radius, speed, width, xPos, yPos) {
this.radius = radius;
this.speed = speed;
this.width = width;
this.xPos = xPos;
this.yPos = yPos;
this.opacity = .1 + Math.random() * .5;
this.counter = 0;
var signHelper = Math.floor(Math.random() * 2);
if (signHelper == 1) {
this.sign = -1;
} else {
this.sign = 1;
}
}
//drawing circle
Circle.prototype.update = function () {
this.counter += this.sign * this.speed;
mainContext.beginPath();
mainContext.arc(this.xPos + Math.cos(this.counter / 100) * this.radius,
this.yPos + Math.sin(this.counter / 100) * this.radius,
this.width,
0,
Math.PI * 2,
false);
mainContext.closePath();
mainContext.fillStyle = 'rgba(255, 255, 51,' + this.opacity + ')';
mainContext.fill();
};
function setupCircles() {
for (var i = 0; i < 25; i++) {
var randomX = Math.round(-200 + Math.random() * 700);
var randomY = Math.round(-200 + Math.random() * 700);
var speed = .2 + Math.random() * 3;
var size = 5 + Math.random() * 100;
var radius = 5 + Math.random() * 100;
var circle = new Circle(radius, speed, size, randomX, randomY);
circles.push(circle);
}
drawAndUpdate();
}
setupCircles();
function drawAndUpdate() {
mainContext.clearRect(0, 0, 1000, 1000);
for (var i = 0; i < circles.length; i++) {
var myCircle = circles[i];
myCircle.update();
}
requestAnimationFrame(drawAndUpdate);
}
jsFiddle : https://jsfiddle.net/CanvasCode/u8avnky2/1/
I added a variable known as color globally, so the fillBackgroundColor can access that instead.
var color = "white";
Then in your drawAndUpdate function we just do a fillRect with the color variable using the canvas width and height and it works.
function drawAndUpdate() {
mainContext.fillStyle = color;
mainContext.fillRect(0, 0, mainCanvas.width, mainCanvas.height);
for (var i = 0; i < circles.length; i++) {
var myCircle = circles[i];
myCircle.update();
}
requestAnimationFrame(drawAndUpdate);
}

Changing shapes using addEventListener in HTML5

I'm trying to change the shape of the particles in this script so that every time you click, the shapes change to a random shape. The shapes I want to do are circles (which they already are), squares, triangles, pentagons, and a four-leaf clover shape without the stem. I want to use the addEventListener method, but i have no idea where to even start with that. Thanks in advance, and here's the code I have so far:
http://jsfiddle.net/eampkcrr/
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var width = window.innerWidth;
var height = window.innerHeight;
var xCirc;
var yCirc;
var rCirc;
var animate = true;
canvas.width = width;
canvas.height = height;
makeParticles();
makeShapes();
function makeParticles() {
xCenter = canvas.width/2;
yCenter = canvas.height/2;
particles = [];
for (var i = 0; i < 3000; i++){
particles.push(new Particle());
}
}
function makeShapes() {
xCenter = canvas.width/2;
yCenter = canvas.height/2;
shapes = [];
shapes.push(new Circle());
}
function Circle() {
var r1 = 150;
var r2 = 1000;
var gradient1 = context.createRadialGradient(width/2, height/2, r1, width/2, height/2, r2);
gradient1.addColorStop(0.2, "yellow");
gradient1.addColorStop(0.8, "purple");
context.fillStyle = gradient1;
context.fillRect(0, 0, canvas.width, canvas.height);
var gradient2 = context.createRadialGradient(width/2, height/2, 120, width/2, height/2, 150);
gradient2.addColorStop(0, "black");
gradient2.addColorStop(.75, "black");
gradient2.addColorStop(1, "orange");
context.beginPath();
context.arc(width/2, height/2, 150, 0, 2 * Math.PI, true);
context.fillStyle = gradient2;
context.fill();
}
function start() {
if(animate){
window.requestAnimationFrame(start);
}
draw();
moveParticles();
}
function Particle() {
this.x = Math.floor((Math.random() * canvas.width) + 1);
this.y = Math.floor((Math.random() * canvas.height) + 1);
this.z = Math.floor((Math.random() * canvas.width));
var grad = context.createRadialGradient(this.x, this.y, Math.floor((Math.random() * 10) + 1), this.x, this.y, Math.floor((Math.random() * 10) + 1));
var colors = ["red", "green", "blue", "orange", "purple", "yellow", "white"];
grad.addColorStop(0, colors[Math.floor(Math.random()*colors.length)]);
grad.addColorStop(1, colors[Math.floor(Math.random()*colors.length)]);
this.color = grad;
this.radius = 1;
}
function draw() {
Circle();
for (var i = 0; i < particles.length; i++){
var p = particles[i];
xP = (xCenter - p.x) * (canvas.width/p.z);
xP += xCenter;
yP = (yCenter - p.y) * (canvas.width/p.z);
yP += yCenter;
rP = (canvas.width/p.z);
context.beginPath();
context.arc(xP, yP, rP, 0, 2 * Math.PI, true);
context.fillStyle = p.color;
context.fill();
xCirc -= p.x;
yCirc -= p.y;
}
}
function moveParticles() {
for (var j = 0; j < particles.length; j++){
var p = particles[j];
p.z -= 2;
if (p.z <= 0){
p.z = canvas.width;
}
}
}
start();
You can listen for click events on the canvas like this:
canvas.onclick=function(){ ... }
To change the particle shape, you can add a draw method to Particle that draws the appropriate shape based on a particle's this.particleType.
function Particle(particleType) {
this.particleType=particleType;
this.x = Math.floor((Math.random() * canvas.width) + 1);
this.y = Math.floor((Math.random() * canvas.height) + 1);
this.z = Math.floor((Math.random() * canvas.width));
var grad = context.createRadialGradient(this.x, this.y, Math.floor((Math.random() * 10) + 1), this.x, this.y, Math.floor((Math.random() * 10) + 1));
var colors = ["red", "green", "blue", "orange", "purple", "yellow", "white"];
grad.addColorStop(0, colors[Math.floor(Math.random()*colors.length)]);
grad.addColorStop(1, colors[Math.floor(Math.random()*colors.length)]);
this.color = grad;
this.radius = 1;
this.draw=function(){
// update position
var xP = (xCenter - this.x) * (canvas.width/this.z);
xP += xCenter;
var yP = (yCenter - this.y) * (canvas.width/this.z);
yP += yCenter;
var rP = (canvas.width/this.z);
// set fillStyle
context.fillStyle = this.color;
// draw on context based on the particle's current shape
switch (this.particleType){
case 'circle':
context.beginPath();
context.arc(xP, yP, rP, 0, 2 * Math.PI, true);
context.fill();
break;
case 'square':
context.fillRect(xP-rP, yP-rP, rP*2, rP*2);
break;
}
// update
xCirc -= this.x;
yCirc -= this.y;
}
}
Then your external function draw simply requests each particle to draw itself:
function draw() {
Circle();
for (var i = 0; i < particles.length; i++){
// request each particle to draw itself
var p = particles[i].draw();
}
}
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var width = window.innerWidth;
var height = window.innerHeight;
var xCirc;
var yCirc;
var rCirc;
var xCenter,yCenter;
var animate = true;
var pTypes=['circle','square'];
var pTypeIndex=0;
canvas.width = width;
canvas.height = height;
makeParticles();
makeShapes();
canvas.onclick=function(){
pTypeIndex++;
if(pTypeIndex>pTypes.length-1){pTypeIndex=0;}
var pType=pTypes[pTypeIndex];
for(var i=0;i<particles.length;i++){
particles[i].particleType=pType;
}
};
start();
function makeParticles() {
xCenter = canvas.width/2;
yCenter = canvas.height/2;
particles = [];
for (var i = 0; i < 500; i++){
particles.push(new Particle(pTypes[pTypeIndex]));
}
}
function makeShapes() {
xCenter = canvas.width/2;
yCenter = canvas.height/2;
shapes = [];
shapes.push(new Circle());
}
function Circle() {
var r1 = 150;
var r2 = 1000;
var gradient1 = context.createRadialGradient(width/2, height/2, r1, width/2, height/2, r2);
gradient1.addColorStop(0.2, "yellow");
gradient1.addColorStop(0.8, "purple");
context.fillStyle = gradient1;
context.fillRect(0, 0, canvas.width, canvas.height);
var gradient2 = context.createRadialGradient(width/2, height/2, 120, width/2, height/2, 150);
gradient2.addColorStop(0, "black");
gradient2.addColorStop(.75, "black");
gradient2.addColorStop(1, "orange");
context.beginPath();
context.arc(width/2, height/2, 150, 0, 2 * Math.PI, true);
context.fillStyle = gradient2;
context.fill();
}
function start() {
if(animate){
window.requestAnimationFrame(start);
}
draw();
moveParticles();
}
function Particle(particleType) {
this.particleType=particleType;
this.x = Math.floor((Math.random() * canvas.width) + 1);
this.y = Math.floor((Math.random() * canvas.height) + 1);
this.z = Math.floor((Math.random() * canvas.width));
var grad = context.createRadialGradient(this.x, this.y, Math.floor((Math.random() * 10) + 1), this.x, this.y, Math.floor((Math.random() * 10) + 1));
var colors = ["red", "green", "blue", "orange", "purple", "yellow", "white"];
grad.addColorStop(0, colors[Math.floor(Math.random()*colors.length)]);
grad.addColorStop(1, colors[Math.floor(Math.random()*colors.length)]);
this.color = grad;
this.radius = 1;
this.draw=function(){
// update position
var xP = (xCenter - this.x) * (canvas.width/this.z);
xP += xCenter;
var yP = (yCenter - this.y) * (canvas.width/this.z);
yP += yCenter;
var rP = (canvas.width/this.z);
// set fillStyle
context.fillStyle = this.color;
// draw on context
switch (this.particleType){
case 'circle':
context.beginPath();
context.arc(xP, yP, rP, 0, 2 * Math.PI, true);
context.fill();
break;
case 'square':
context.fillRect(xP-rP, yP-rP, rP*2, rP*2);
break;
}
// update
xCirc -= this.x;
yCirc -= this.y;
}
}
function draw() {
Circle();
for (var i = 0; i < particles.length; i++){
var p = particles[i].draw();
}
}
function moveParticles() {
for (var j = 0; j < particles.length; j++){
var p = particles[j];
p.z -= 2;
if (p.z <= 0){
p.z = canvas.width;
}
}
}
<h4>Click to change shapes.</h4>
<canvas id="canvas" width=300 height=300></canvas>
[ Fixed "yip" in circle <--> square conversion -- Thanks #Kaiido ]

How do i bind onclick event to piechart segment?

How do i bind onclick event to piechart segment?
https://github.com/sauminkirve/HTML5/blob/master/PieChart/piechart.html
A pie chart segment is really a wedge. You have several ways to hit-test a wedge.
One way is the math way:
Test if the mouse is within the radius of a circle created by the wedges.
If the radius test is true, then calculate the angle of the mouse versus the circle's centerpoint.
Compare that angle to each wedge. If the angle is between the starting and ending angle of a specific wedge's arc, then the mouse is inside that wedge.
Another way is to use canvas's built in path hit-testing method: isPointInPath
Redefine one wedge. There's no need to actually stroke or fill that wedge. Just do the commands from beginPath to closePath.
Use context.isPointInPath(mouseX,mouseY) to hit-test if the mouse is inside that wedge.
If isPointInPath returns true, you've discovered the wedge under the mouse. If not, then redefine & hit-test each of the other wedges.
Here's something I coded a while back that hit-tests the wedges of a pie chart when hovering and moves the wedge out of the pie when a wedge is clicked.
It uses the isPointInPath method to do the hit-testing:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.lineJoin = "round";
var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();
function Wedge(cx, cy, radius, startAngleDeg, endAngleDeg, fill, stroke, linewidth) {
this.cx = cx;
this.cy = cy;
this.radius = radius;
this.startAngle = startAngleDeg * Math.PI / 180;
this.endAngle = endAngleDeg * Math.PI / 180;
this.fill = fill;
this.stroke = stroke;
this.lineWidth = linewidth;
this.offsetX = 0;
this.offsetY = 0;
this.rr = radius * radius;
this.centerX = cx;
this.centerY = cy;
this.midAngle = this.startAngle + (this.endAngle - this.startAngle) / 2;
this.offsetDistance = 15;
this.explodeX = this.offsetDistance * Math.cos(this.midAngle);
this.explodeY = this.offsetDistance * Math.sin(this.midAngle);
this.isExploded = false;
};
Wedge.prototype.draw = function(fill, stroke) {
this.define();
this.fillStroke(fill, stroke);
ctx.beginPath();
ctx.arc(this.cx, this.cy, this.radius, 0, Math.PI * 2);
ctx.closePath();
ctx.lineWidth = 0.50;
ctx.stroke();
}
Wedge.prototype.fillStroke = function(fill, stroke) {
ctx.fillStyle = fill || this.fill;
ctx.fill();
ctx.strokeStyle = stroke, this.stroke;
ctx.lineWidth = this.lineWidth;
ctx.stroke();
}
Wedge.prototype.define = function() {
var x = this.cx + this.offsetX;
var y = this.cy + this.offsetY;
ctx.beginPath();
ctx.arc(x, y, this.radius, this.startAngle, this.endAngle);
ctx.lineTo(x, y);
ctx.closePath();
}
Wedge.prototype.ptAtAngle = function(radianAngle) {
var xx = (this.cx + this.offsetX) + this.radius * Math.cos(radianAngle);
var yy = (this.cy + this.offsetY) + this.radius * Math.sin(radianAngle);
return ({
x: x,
y: y
});
}
Wedge.prototype.explode = function(isExploded) {
this.isExploded = isExploded;
this.offsetX = isExploded ? this.explodeX : 0;
this.offsetY = isExploded ? this.explodeY : 0;
this.draw();
}
Wedge.prototype.isPointInside = function(x, y) {
var dx = x - (this.cx + this.offsetX);
var dy = y - (this.cy + this.offsetY);
if (dx * dx + dy * dy > this.rr) {
return (false);
}
var angle = (Math.atan2(dy, dx) + Math.PI * 2) % (Math.PI * 2);
return (angle >= this.startAngle && angle <= this.endAngle);
}
Wedge.prototype.marker = function(pos) {
ctx.beginPath();
ctx.arc(pos.x, pos.y, 3, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = "red";
ctx.fill();
}
function handleMouseDown(e) {
e.preventDefault();
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
clear();
for (var i = 0; i < wedges.length; i++) {
var wedge = wedges[i].wedge;
if (wedge.isPointInside(mouseX, mouseY)) {
wedge.explode(!wedge.isExploded);
}
wedge.draw();
}
}
function handleMouseUp(e) {
e.preventDefault();
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// Put your mouseup stuff here
isDown = false;
}
function handleMouseOut(e) {
e.preventDefault();
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// Put your mouseOut stuff here
isDown = false;
}
function handleMouseMove(e) {
e.preventDefault();
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
for (var i = 0; i < wedges.length; i++) {
var wedge = wedges[i].wedge;
if (wedge.isPointInside(mouseX, mouseY)) {
wedge.draw("black");
} else {
wedge.draw();
}
}
}
$("#canvas").mousedown(function(e) {
handleMouseDown(e);
});
$("#canvas").mousemove(function(e) {
handleMouseMove(e);
});
$("#canvas").mouseup(function(e) {
handleMouseUp(e);
});
$("#canvas").mouseout(function(e) {
handleMouseOut(e);
});
function clear() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
var PI2 = Math.PI * 2;
var cx = 150;
var cy = 150;
var r = 100;
var line = 2;
var stroke = "black";
var wedges = [];
wedges.push({
percent: 18,
fill: "red"
});
wedges.push({
percent: 30,
fill: "blue"
});
wedges.push({
percent: 25,
fill: "green"
});
wedges.push({
percent: 13,
fill: "purple"
});
wedges.push({
percent: 14,
fill: "gold"
});
var rAngle = 0;
for (var i = 0; i < wedges.length; i++) {
var wedge = wedges[i];
var angle = 360 * wedge.percent / 100;
wedge.wedge = new Wedge(cx, cy, r, rAngle, rAngle + angle, wedge.fill, "black", 1);
wedge.wedge.draw();
rAngle += angle;
}
window.onscroll = function(e) {
var BB = canvas.getBoundingClientRect();
offsetX = BB.left;
offsetY = BB.top;
}
body {
background-color: ivory;
}
#canvas {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Hover wedge to highlight it<br>Click wedge to explode that wedge</h4>
<canvas id="canvas" width=300 height=300></canvas>

Resources