Highlighting part in canvas arc using Javascript or jQuery - javascript

I have drawn an arc on a canvas, this arc has 3 parts. If user clicks on any one of the part then my code will show an alert with the x and y position. Now I want to highlight this clicked region. How do I do that?
This code draws the arc:
var canvas = document.getElementById('zone');
if(!canvas.getContext){
alert("canvas not supported");
}
else {
var canvasContent = canvas.getContext('2d');
var zoneX = canvas.width / 2;
var zoneY = canvas.height / 2;
var radius = 100;
canvasContent.beginPath();
canvasContent.arc(zoneX,zoneY, radius, 0, 2 * Math.PI, false);
canvasContent.fillStyle = 'white';
canvasContent.fill();
canvasContent.lineWidth = 1;
canvasContent.strokeStyle = '#333';
canvasContent.stroke();
drawLine(canvasContent);
$('#zone').on('click',function(e){
var clickX = e.clientX;
var clickY = e.clientY;
alert(clickX + " : "+clickY);
});
}
function drawLine(canvasContentDrawLine) {
canvasContentDrawLine.beginPath();
canvasContentDrawLine.moveTo(canvas.width / 2, canvas.width / 2);
canvasContentDrawLine.lineTo(canvas.width / 2.5, canvas.height / 4.7);
canvasContentDrawLine.moveTo(338, 200 );
canvasContentDrawLine.lineTo(canvas.width / 2.5, canvas.height / 4.7);
canvasContentDrawLine.stroke();
}
Fiddle
This code will show an alert with the position:
$('#zone').on('click',function(e){
var clickX = e.clientX;
var clickY = e.clientY;
alert(clickX + " : "+clickY);
});

Related

It Was Working Earlier, But Somehow I Broke It

HTML:
<canvas id="cnvs" width=1 height=250 style="border:1px solid #000000;"></canvas>
JS:
// Square size
var squareSize = 50;
// Trail size (smaller number means more trail)
var globalAlpha = 0.0025;
// Text
var text = "Lorem Ipsum";
console.clear();
var cnvs = document.getElementById("canvas");
var ctx = cnvs.getContext("2d");
var windW = window.innerWidth;
cnvs.width = windW - 20;
var cnvsH = cnvs.height;
function MouseMove(XMouse, YMouse) {
console.clear();
ctx.fillStyle = "#000000";
ctx.globalAlpha = 1;
ctx.fillRect(
XMouse - 10 - squareSize / 2,
YMouse - 10 - squareSize / 2,
squareSize,
squareSize
);
}
function handler(e) {
e = e || window.event;
var pageX = e.pageX;
var pageY = e.pageY;
if (pageX === undefined) {
pageX =
e.clientX +
document.body.scrollLeft +
document.documentElement.scrollLeft;
pageY =
e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
console.log(pageX, pageY);
MouseMove(pageX, pageY);
}
if (document.attachEvent) document.attachEvent("onmousemove", handler);
else document.addEventListener("mousemove", handler);
var loop = setInterval(function() {
ctx.fillStyle = "#FFFFFF";
ctx.globalAlpha = globalAlpha;
ctx.fillRect(0, 0, windW, CnvsH);
ctx.font = "100px Arial";
ctx.globalAlpha = 1;
ctx.fillStyle = "#000000";
ctx.textAlign = "center";
ctx.fillText(text, windW / 2, cnvsH / 2);
}, 10);
What's Expected is a Square That Fades Away, With Text In The Center
The square is drawn correctly, but the fade doesn't happen, and the text doesn't appear.
I use codepen for my coding.
It was working, but I think I tried adding comments, and something I did while doing that broke it. I haven't graduated high school so I don't have any college experience and all my coding is self-taught and tutorials (Thanks w3schools.com)
in your code are 2 mistakes.
First:
"var cnvs = document.getElementById("canvas");"
Your ID is - "var cnvs = document.getElementById("cnvs");"
And secound:
In your "var loop" there is a typo mistake for
"ctx.fillRect(0, 0, windW, CnvsH);" it should be "cnvsH" and not "CnvsH".
right -> ctx.fillRect(0, 0, windW, cnvsH);
Gl and try to use a Debugger.

How to add SVG image to javascript html5 canvas animation?

I currently have a rotating bouncing ball within an html5 canvas and I am looking to insert an SVG image inside the ball that moves and rotates with it
I have this code from researching this but unsure if this is correct
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
img.src = "";
Does anyone have any suggestion on how I might achieve this?
Here is my code
<canvas id="myCanvas"></canvas>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height / 2;
// SPEED
var dx = 4;
var dy = -4;
var radius = 120;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fillStyle = "#9370DB";
ctx.fill();
ctx.closePath();
if (x + dx > canvas.width - radius) {
dx = -dx;
}
if (x + dx < radius) {
dx = -dx;
}
if (y + dy > canvas.height - radius) {
dy = -dy;
}
if (y + dy < radius) {
dy = -dy;
}
x += dx;
y += dy;
}
window.addEventListener('resize', resizeCanvas, false);
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
resizeCanvas();
x = canvas.width / 2;
y = canvas.height / 2;
setInterval(draw, 10);
var img = new Image();
img.src = ""; // Put the path to you SVG image here.
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
This should work
One way of doing it would be putting the image hidden in the HTML. In this case the image is an svg as data uri and has an id="apple" and you can say:
var img = apple;
To draw the image inside the ball you need to use the center of the ball, for example like this:
ctx.drawImage(img, x-img.width/2,y-img.height/2)
Also instead of using setInterval I'm using requestAnimationFrame and the image is not getting out of the screen on resize. I hope you will find my answer useful.
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height / 2;
var rid = null;// request animation id
// SPEED
var dx = 4;
var dy = -4;
var radius = 120;
var img = apple;// the image is the one with the id="apple"
function draw() {
rid = window.requestAnimationFrame(draw);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fillStyle = "#9370DB";
ctx.fill();
ctx.closePath();
//draw the image in the center of the ball
ctx.drawImage(img, x-img.width/2,y-img.height/2)
if (x + dx > canvas.width - radius) {
dx = -dx;
}
if (x + dx < radius) {
dx = -dx;
}
if (y + dy > canvas.height - radius) {
dy = -dy;
}
if (y + dy < radius) {
dy = -dy;
}
x += dx;
y += dy;
}
window.addEventListener('resize', resizeCanvas, false);
function resizeCanvas() {
//stop the animation
if(rid){window.cancelAnimationFrame(rid); rid= null;}
//get the size of the canvas
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
x = canvas.width / 2;
y = canvas.height / 2;
//restart the animation
draw()
}
window.setTimeout(function() {
resizeCanvas();
window.addEventListener('resize', resizeCanvas, false);
}, 15);
<canvas id="myCanvas">
<img id="apple" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' version='1.1' id='Layer_1' x='0px' y='0px' width='106px' height='122px' viewBox='41 54 106 122'%3E%3Cg%3E%3Cpath fill='%23FFFFFF' stroke='%23ED1D24' stroke-width='2' stroke-miterlimit='10' d='M143.099,93.757c0,0-14.173,8.549-13.724,23.173 c0.449,14.624,11.954,23.413,15.974,24.073c1.569,0.258-9.245,22.049-15.984,27.448c-6.74,5.4-13.714,6.524-24.513,2.25c-10.8-4.275-18.449,0.275-24.749,2.612c-6.299,2.337-13.949-0.137-24.298-14.987c-10.349-14.849-21.823-49.271-6.074-66.146c15.749-16.874,33.298-10.124,38.022-7.875c4.725,2.25,13.05,2.025,22.499-2.25C119.7,77.782,138.374,86.782,143.099,93.757z'/%3E%3C/g%3E%3Cg%3E%3Cpath fill='%23FFFFFF' stroke='%23ED1D24' stroke-width='2' stroke-miterlimit='10' d='M118.575,54.609c0,0,0.9,5.625-1.35,10.349 s-10.718,20.936-22.994,17.999c-0.308-0.073-2.102-5.506,0.532-11.027C98.48,64.138,108.171,55.399,118.575,54.609z'/%3E%3C/g%3E%3C/svg%3E" />
</canvas>
Please run the code on full page.

How to make one drawing follow the other (html canvas)

I have two drawings: one arc and one circle and I want the circle to follow the end of the arc. Basically, i need to fetch the x&y of the endAngle of the arc so I would use it on the circle to follow it.
//Arc
context.beginPath();
var x2 = canvas.width / 2;
var y2 = canvas.height / 2;
var radius2 = 215;
var startAngle2 = 1.5 * Math.PI;
var endAngle2= 2.3 * Math.PI;
var counterClockwise2 = false;
context.arc(x2, y2, radius2, startAngle2, endAngle2, counterClockwise2);
context.lineWidth = 10;
context.strokeStyle = "blue";
context.stroke();
//Circle
context.beginPath();
var x3 = x2+ 130;
var y3 = y2 + 200;
var radius3 = 20;
var startAngle3 = 0 * Math.PI;
var endAngle3 = 2 * Math.PI;
var counterClockwise3 = false;
context.arc(x3, y3, radius3, startAngle3, endAngle3, counterClockwise3);
context.lineWidth = 5;
context.strokeStyle = "yellow";
context.stroke();
If you want to get the x,y coordinates of the end of the arc, you should work with cos for x and sin for y.
Get the end of your arc (x,y) like so:
var x3 = canvas.width / 2 + radius2*Math.cos(endAngle2);
var y3 = canvas.height / 2 + radius2*Math.sin(endAngle2);
It's easier to use ctx.rotate(angle);
The center of the rotation is the origin of the canvas identified by 0,0. In order to choose another one you need to use ctx.translate(x, y); where x,y are the coordinates of the center of the rotation hence
context.translate(x1,y1)
context.rotate(20*Math.PI/180)
Finally, you need to change your coordinates to refer to the new center
context.arc(x2, y2, radius2, startAngle2, endAngle2, counterClockwise2);
...
....
var x3 = x2 + 130;
var y3 = y2 + 200;
becomes
context.arc(0, 0, radius2, startAngle2, endAngle2, counterClockwise2);
....
...
var x3 = 130;
var y3 = 200;
Here's the full code:
var canvas=document.getElementById("clock");
var context = canvas.getContext('2d');
context.beginPath();
var x1 = canvas.width/2;
var y1 = canvas.height/2;
var radius1 = 200;
var startAngle1 = 0 * Math.PI;
var endAngle1 = 2 * Math.PI;
var counterClockwise1 = false;
context.arc(x1, y1, radius1, startAngle1, endAngle1, counterClockwise1);
context.lineWidth = 20;
context.strokeStyle = 'black';
context.stroke();
context.font = "bold 76px Arial";
context.textAlign="center";
context.textBaseline="middle";
context.fillText("25:00", canvas.width/2, canvas.height/2);
context.beginPath();
context.translate(x1,y1)
context.rotate(Math.PI)
var radius2 = 215;
var startAngle2 = 1.5 * Math.PI;
var endAngle2 = 2.3 * Math.PI;
var counterClockwise2 = false;
context.arc(0, 0, radius2, startAngle2, endAngle2, counterClockwise2);
context.lineWidth = 10;
context.strokeStyle = "blue";
context.stroke();
context.beginPath();
var x3 = 130;
var y3 = 200;
var radius3 = 20;
var startAngle3 = 0 * Math.PI;
var endAngle3 = 2 * Math.PI;
var counterClockwise3 = false;
context.arc(x3, y3, radius3, startAngle3, endAngle3, counterClockwise3);
context.lineWidth = 5;
context.strokeStyle = "yellow";
context.stroke();
body {
background-color: #50B3B9;
}
#clock {
background-color: red;
position:relative;
}
#time {
position:absolute;
top:0px;
}
----------
<div class="container">
<canvas id="clock" width="600" height="600">
<div id="time">25:00</div>
</canvas>
</div>

draw circle in canvas with click option

I write this javascript code :
<script>
var canvas = document.getElementById("canvas");
var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
function handleMouseDown(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
$("#downlog").html("Down: " + mouseX + " / " + mouseY);
}
$("#canvas").mousedown(function(e) {
handleMouseDown(e);
});
</script>
in this code , I detect a coordinate with mouse click .
I want draw a circle around the this coordinate that when I click on circle , do something (for ex. open google.com)
note : I do this with jquery in html 4 and with area map , but I do not have any idea in canvas .
I can't tell if you want to draw a circle, detect a mouse click in a circle or both.
Draw a circle:
var context=canvas.getContext("2d");
ctx.beginPath();
//Draw a circle around a mouse click
//ctx.arc(x-position, y-position, radius, start-angle, end-angle);
ctx.arc(mouseX, mouseY, 30, 0, 2*Math.PI);
ctx.stroke();
Detect a mouse click within a circle:
//circleX and circleY are the coordinats of the center
var y = mouseY - circleY;
var x = mouseX - circleX;
var dist = Math.sqrt(y*y + x*x);
if (dist < circleRadius) {
// Do whatever you want to do
}
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 70;
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();

Adding html content on a moving element in Canvas

How I can add Html content on a moving element in the Canvas, like this one
http://www.html5canvastutorials.com/labs/html5-canvas-harmonic-oscillator/
where I need to display my link or button on the moving block attached to the spring. Generally for static canvas elements we can use Z-index or overlapping techniques, but these don't work in this case.
Any solutions ?
Check if the following script works:
<script src="http://www.html5canvastutorials.com/libraries/kinetic2d-v1.0.3.js">
</script>
<script>
var button = {
x: 0,
y: 0,
size: 16,
width: 0,
height: 0,
padding: 4,
hover: false,
text: "Click Me",
onclick: function (e) {
// put your event handler code here
}
};
function drawSpring(canvas, context){
context.beginPath();
context.moveTo(0, 0);
for (var y = 0; y < 200; y++) {
// Sine wave equation
var x = 30 * Math.sin(y / 9.05);
context.lineTo(x, y);
}
}
function drawWeight(canvas, context, y){
var size = 100;
context.save();
context.fillStyle = "red";
context.fillRect(-size / 2, 0, size, size);
context.restore();
canvas.fillText(button.text, 0, 0);
button.x = ((canvas.width - button.width) / 2) - button.padding;
button.y = (y + (size - button.height) / 2) - button.padding;
}
window.onload = function(){
var kin = new Kinetic_2d("myCanvas");
var canvas = kin.getCanvas();
var context = kin.getContext();
context.font = button.size + "px Verdana";
context.textAlign = "center";
context.textBaseline = "top";
button.width = 2 * button.padding + context.measureText(button.text);
button.height = 2 * button.padding + button.size;
var theta = 0;
var curleft = 0;
var curtop = 0;
var obj = canvas;
do {
curleft += object.offsetLeft;
curtop += object.offsetTop;
} while (obj = obj.offsetParent);
canvas.addEventListener("mousemove", function (e) {
context.beginPath();
context.rect(button.x, button.y, button.width, button.height);
button.hover = context.isPointInPath(e.pageX - curleft, e.pageY - curtop);
}, false);
canvas.addEventListener("click", function (e) {
if (button.hover) button.onclick(e);
}, false);
kin.setDrawStage(function(){
theta += this.getTimeInterval() / 400;
var scale = 0.8 * (Math.sin(theta) + 1.3);
this.clear();
context.save();
context.translate(canvas.width / 2, 0);
context.save();
context.scale(1, scale);
drawSpring(canvas, context);
context.restore();
context.lineWidth = 6;
context.strokeStyle = "#0096FF"; // blue-ish color
context.stroke();
context.translate(0, 200 * scale);
drawWeight(canvas, context, 200 * scale);
context.restore();
});
kin.startAnimation();
};
</script>

Categories

Resources