Ive tried solving the problem, and i cant seem to find its solution. A few hours of fiddling around later, ive found out that the problem is within the button tag or the onclick attribute (Correct me if im wrong).
My aim is to make the white dot move via buttons
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
window.onload = function()
{
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 345;
canvas.height = 410;
canvas.style.border = "1px solid white";
var left = document.getElementById("left");
left.onclick = "playerLeft()";
var x = Math.round(canvas.width/2);
var y = Math.round(canvas.width/2);
var rectWidth = 5, rectHeight = 5;
var fps = 30, frames = 1000/fps;
var colour = "white";
var trailColour = "blue";
ctx.fillStyle = colour;
ctx.fillRect(x,y,rectWidth,rectHeight);
function playerLeft() {
ctx.fillStyle = trailColour;
ctx.fillRect(x,y,rectWidth,rectHeight);
x -= 6;
ctx.fillStyle = colour;;
ctx.fillRect(x,y,rectWidth,rectHeight);
}
function playerRight() {
ctx.fillStyle = trailColour;
ctx.fillRect(x,y,rectWidth,rectHeight);
x += 6;
ctx.fillStyle = colour;
ctx.fillRect(x,y,rectWidth,rectHeight);
}
function playerUp() {
ctx.fillStyle = trailColour;
ctx.fillRect(x,y,rectWidth,rectHeight);
y -= 6;
ctx.fillStyle = colour;
ctx.fillRect(x,y,rectWidth,rectHeight);
}
function playerDown() {
ctx.fillStyle = trailColour;
ctx.fillRect(x,y,rectWidth,rectHeight);
y += 6;
ctx.fillStyle = colour;
ctx.fillRect(x,y,rectWidth,rectHeight);
}
}
</script>
</head>
<body style="background-color: black">
<canvas id="canvas"></canvas>
<div style="text-align: center; padding: 5px">
<button id="left">Left</button>
<button id="up">Up</button>
<button id="down">Down</button>
<button id="right">Right</button>
</div>
</body>
</html>
One of the many reasons not to use onxyz="..."-style event handlers is that any functions you call from them must be globals. Your functions aren't, they're local to the window.onload callback.
Instead, just assign the function reference directly, either somewhat old-fashioned:
left.onclick = playerLeft;
or using more modern techniques that allow for multiple handlers:
left.addEventListener("click", playerLeft);
Just call the function without parenthesis.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
window.onload = function() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 345;
canvas.height = 410;
canvas.style.border = "1px solid white";
var left = document.getElementById("left");
left.addEventListener("click", playerLeft);
var x = Math.round(canvas.width/2);
var y = Math.round(canvas.width/2);
var rectWidth = 5, rectHeight = 5;
var fps = 30, frames = 1000/fps;
var colour = "white";
var trailColour = "blue";
ctx.fillStyle = colour;
ctx.fillRect(x,y,rectWidth,rectHeight);
function playerLeft() {
ctx.fillStyle = trailColour;
ctx.fillRect(x,y,rectWidth,rectHeight);
x -= 6;
ctx.fillStyle = colour;;
ctx.fillRect(x,y,rectWidth,rectHeight);
}
function playerRight() {
ctx.fillStyle = trailColour;
ctx.fillRect(x,y,rectWidth,rectHeight);
x += 6;
ctx.fillStyle = colour;
ctx.fillRect(x,y,rectWidth,rectHeight);
}
function playerUp() {
ctx.fillStyle = trailColour;
ctx.fillRect(x,y,rectWidth,rectHeight);
y -= 6;
ctx.fillStyle = colour;
ctx.fillRect(x,y,rectWidth,rectHeight);
}
function playerDown() {
ctx.fillStyle = trailColour;
ctx.fillRect(x,y,rectWidth,rectHeight);
y += 6;
ctx.fillStyle = colour;
ctx.fillRect(x,y,rectWidth,rectHeight);
}
}
</script>
</head>
<body style="background-color: black">
<canvas id="canvas"></canvas>
<div style="text-align: center; padding: 5px">
<button id="left">Left</button>
<button id="up">Up</button>
<button id="down">Down</button>
<button id="right">Right</button>
</div>
</body>
</html>
Related
How do I make a row of triangles?
Here's the code I have so far.
I'm new I don't know what to do here.
function showDrawing() {
let coolCanvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
ctx.lineWidth = 5;
for (let i = 0; i < 5; i += 1) {
ctx.beginPath();
ctx.moveTo(126, 300);
ctx.lineTo(200, 400);
ctx.lineTo(50, 400);
ctx.closePath();
ctx.strokeStyle = 'blue';
ctx.fillStyle = 'purple';
ctx.fill();
ctx.stroke();
}
}
<canvas id="canvas" width="1500" height="700" style="border:3px solid #000000;">
</canvas>
<button onclick="showDrawing()">Drawing</button>
You can use the iteration (i) and multiply it by the spacing you want and add it to the x value.
function showDrawing() {
let coolCanvas = document.getElementById("canvas");
let ctx = coolCanvas.getContext("2d");
ctx.lineWidth = 5;
for (let i = 0; i < 5; i += 1) {
ctx.beginPath();
ctx.moveTo(126+(i*170), 300);
ctx.lineTo(200+(i*170), 400);
ctx.lineTo(50+(i*170), 400);
ctx.closePath();
ctx.strokeStyle = 'blue';
ctx.fillStyle = 'purple';
ctx.fill();
ctx.stroke();
}
}
<canvas id="canvas" width="1500" height="700" style="border:3px solid #000000;">
</canvas>
<button onclick="showDrawing()">Drawing</button>
You should use a variable to add to the X positions and increment as you want :
function showDrawing() {
let coolCanvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
let delta = 0;
ctx.lineWidth = 5;
for (let i = 0; i < 5; i += 1) {
ctx.beginPath();
ctx.moveTo(126 + delta, 300);
ctx.lineTo(200 + delta, 400);
ctx.lineTo(50 + delta, 400);
ctx.closePath();
ctx.strokeStyle = 'blue';
ctx.fillStyle = 'purple';
ctx.fill();
ctx.stroke();
delta += 174;
}
}
<canvas id="canvas" width="1500" height="700" style="border:3px solid #000000;">
</canvas>
<button onclick="showDrawing()">Drawing</button>
You can create a separate function to handle drawing the triangles, then pass in the xStart as the base x-coordinate value for any triangle to be drawn. Then in the showDrawing function, run a loop and multiply the i variable to some spacing value. In your code, your triangle is 150 pixels wide and starts at x-value of 50, so I multiplied the i value by 200 for consistency in my solution code.
Additionally, I highly advise using the variable name you set (coolCanvas) as the reference to the canvas or set this variable to be named canvas instead. If you only ever set the canvas once and reference it once, you can probably skip setting the reference altogether:
let ctx = document.getElementById("canvas").getContext("2d");
function drawTriangle(ctx, xStart) {
ctx.lineWidth = 5;
ctx.strokeStyle = "blue";
ctx.fillStyle = "purple";
ctx.beginPath();
ctx.moveTo(xStart + 126, 300);
ctx.lineTo(xStart + 200, 400);
ctx.lineTo(xStart + 50, 400);
ctx.closePath();
ctx.fill()
ctx.stroke();
}
function showDrawing() {
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
ctx.lineWidth = 5;
for (let i = 0; i < 5; i += 1) {
drawTriangle(ctx, i * 200);
}
}
document.getElementById("draw").addEventListener("click", showDrawing);
canvas {
border: 3px solid #000000;
}
<div><button id="draw">Drawing</button></div>
<div><canvas id="canvas" width="1500" height="700"></canvas></div>
I'm drawing canvas and have put in some shapes and text and I want to move the text inside the canvas like the text bar animated from left to right
As you can see, when I'm moving the text is moving not like it supposed to be.
How can I fix it?
<script>
var pointX, pointY , w , h ;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
c.width = window.innerWidth;
c.height = window.innerHeight;
ctx.clearRect(0, 0, ctx.canvas.width,ctx.canvas.height);
ctx.beginPath();
ctx.strokeStyle='red';
ctx.strokeRect(10,0,720,576);
ctx.closePath();
ctx.beginPath();
ctx.fillStyle='grey';
ctx.fillRect(10,525,720,50);
ctx.closePath();
ctx.beginPath();
var start = 10;
setInterval(function(){
start += 4;
ctx.font = "30px Arial";
ctx.fillStyle = "red";
ctx.textAlign = "left";
ctx.fillText("Hello World",start, 560);
}, 40);
ctx.closePath();
pointX = 690;
pointY = 550;
w = 30;
h = 20;
ctx.beginPath();
ctx.strokeStyle='red';
ctx.strokeRect(pointX,pointY,w,h);
ctx.closePath();
</script>
<!DOCTYPE html>
<html>
<head>
<script src ="js/jquery-3.3.1.min.js" ></script>
<link href ="css/bootstrap.min.css" rel="stylesheet">
<script src ="js/bootstrap.min.js" ></script>
<meta charset="utf-8">
<meta name = "viewport" content = "width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0"/>
</head>
<body dir="rtl" id="tbodyid">
<canvas id="myCanvas" width="1050" height="1050" class="col-12 col-s-12" >
</canvas>
</body>
</html>
As I've commented, inside your setInterval function you should add ctx.clearRect(0,0,c.width,c.height). Also you have to redraw everything else. So I've putted your shapes inside functions, and I'm calling those functions inside setInterval too.
var pointX, pointY , w , h ;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
c.width = 1000;
c.height = 650;
ctx.clearRect(0, 0, ctx.canvas.width,ctx.canvas.height);
function drawShape1(){
ctx.beginPath();
ctx.strokeStyle='red';
ctx.strokeRect(10,0,720,576);
ctx.closePath();
ctx.beginPath();
ctx.fillStyle='grey';
ctx.fillRect(10,525,720,50);
ctx.closePath();
}
function drawShape2(){
pointX = 690;
pointY = 550;
w = 30;
h = 20;
ctx.beginPath();
ctx.strokeStyle='red';
ctx.strokeRect(pointX,pointY,w,h);
ctx.closePath();
}
var start = 10;
setInterval(function(){
ctx.clearRect(0,0,c.width,c.height)
drawShape1()
start += 4;
ctx.font = "30px Arial";
ctx.fillStyle = "red";
ctx.textAlign = "left";
ctx.fillText("Hello World",start, 560);
drawShape2()
}, 40);
<canvas id="myCanvas" width="1000" height="650" class="col-12 col-s-12" ></canvas>
However if you want to try using requestAnimationFrame instead of setInterval this is how to do it:
Since requestAnimationFrame runs at 60 frames per sec I've changed start += 4; to start += 2;
var pointX, pointY , w , h ;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
c.width = 1000;
c.height = 650;
ctx.clearRect(0, 0, ctx.canvas.width,ctx.canvas.height);
function drawShape1(){
ctx.beginPath();
ctx.strokeStyle='red';
ctx.strokeRect(10,0,720,576);
ctx.closePath();
ctx.beginPath();
ctx.fillStyle='grey';
ctx.fillRect(10,525,720,50);
ctx.closePath();
}
function drawShape2(){
pointX = 690;
pointY = 550;
w = 30;
h = 20;
ctx.beginPath();
ctx.strokeStyle='red';
ctx.strokeRect(pointX,pointY,w,h);
ctx.closePath();
}
var start = 10;
function frame(){
requestAnimationFrame(frame)
ctx.clearRect(0,0,c.width,c.height)
drawShape1()
start += 2;
ctx.font = "30px Arial";
ctx.fillStyle = "red";
ctx.textAlign = "left";
ctx.fillText("Hello World",start, 560);
drawShape2()
}
frame()
<canvas id="myCanvas" width="1050" height="1050" class="col-12 col-s-12" >
</canvas>
<canvas id="myCanvas" width="1050" height="1050" class="col-12 col-s-12" >
</canvas>
<script>
var pointX, pointY , w , h ;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
c.width = 1000;
c.height = 650;
ctx.clearRect(0, 0, ctx.canvas.width,ctx.canvas.height);
function drawShape1(){
ctx.beginPath();
ctx.strokeStyle='red';
ctx.strokeRect(10,0,720,70);
ctx.closePath();
ctx.beginPath();
ctx.fillStyle='gold';
ctx.fillRect(10,10,720,50);
ctx.closePath();
}
function drawShape2(){
pointX = 690;
pointY = 30;
w = 30;
h = 20;
ctx.beginPath();
ctx.strokeStyle='red';
ctx.strokeRect(pointX,pointY,w,h);
ctx.closePath();
}
var start = 10;
function frame(){
requestAnimationFrame(frame)
ctx.clearRect(0,0,c.width,c.height)
drawShape1()
start += 2;
ctx.font = "30px Arial";
ctx.fillStyle = "red";
ctx.textAlign = "left";
ctx.fillText("Hello World",start, 50);
if (start > 576) start = 0;
drawShape2()
}
frame()
</script>
I have a Javascript program working in three different places: here,
here, and here.
But I don't know how would I put them in one file. This is where I am at right now.
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<style>
body {
background-color:#E4E0FF;
}
#canvas {
border:10px solid red;
background-color:white;
}
#canvas2 {
border:10px solid red;
background-color:white;
}
#canvas3 {
border:10px solid red;
background-color:white;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="300">
</canvas>
<canvas id="canvas2" width="400" height="300">
</canvas>
<canvas id="canvas3" width="400" height="300">
</canvas>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script type="text/javascript">
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();
var toggle=0;
var x=150;
var y=100;
var w=100;
var h=100;
var r=60;
var wasInside=false;
ctx.fillStyle = "#000000";
ctx.fillRect(x, y, w, h);
function changeColor() {
if (toggle == 0) {
ctx.fillStyle = "#04B45F";
toggle = 1;
} else if (toggle ==1){
ctx.fillStyle = "#04B45F";
toggle = 2;
}else if (toggle == 2){
ctx.fillStyle = "#0000FF";
toggle = 3;
}else if (toggle == 3){
ctx.fillStyle == "#190707";
toggle = 4;
}else if (toggle == 4){
ctx.fillStyle = "#210B61";
toggle = 5;
}else if (toggle == 5){
ctx.fillStyle = "#FA58AC";
toggle = 6;
}else if (toggle ==6){
ctx.fillStyle = "#FFFF00";
toggle = 7;
}else{
ctx.fillStyle = "#F5A9D0";
toggle = 0;
}
ctx.fillRect(x, y, w, h);
}
function changeRadius() {
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0,0, 400, 300);
r = Math.floor((Math.random() * 80) + 20);
ctx.beginPath();
ctx.arc(200, 150, r, 0, 2 * Math.PI);
ctx.stroke();
}
function changeWidth() {
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0,0, 400, 300);
width = Math.floor((Math.random()*50)+1);
ctx.lineWidth=width;
ctx.stroke();
}
function handleMouseMove(e) {
var mx = parseInt(e.clientX - offsetX);
var my = parseInt(e.clientY - offsetY);
var isInsideNow = (mx > x && mx < x + w && my > y && my <= y + h);
if (isInsideNow && !wasInside) {
changeColor();
wasInside = true;
} else if (!isInsideNow && wasInside) {
wasInside = false;
}
}
$("#canvas").mousemove(function (e) {
handleMouseMove(e);
});
$("#canvas2").mousemove(function (e) {
handleMouseMove(e);
});
$("#canvas3").mousemove(function (e) {
handleMouseMove(e);
});
</script>
</body>
</html>
So, how would I tell the program to do circle thing in 2nd canvas and line in 3rd canvas???
I haven't called the changeWidth and changeRadius functions yet, because it'll just do it in the first canvas making a mess.
I just need something in this part of the code to call different functions in different canvas's
if (isInsideNow && !wasInside) {
changeColor();
wasInside = true;
} else if (!isInsideNow && wasInside) {
wasInside = false;
}
I'm not a canvas expert, but just for giving you an idea, check this FIDDLE
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
inspect these 2 lines, the context ctx wil draw in the canvas with id=canvas. you can create other contex variables to draw in the other canvas or reuse the same.
updated FIDDLE
Update for the update: FIDDLE
I want to programm this cool visualization with javascrip:
http://imgur.com/ZCUW7js
I have this: http://test.wikunia.de/pi/ but unfortunately I have no idea how to draw the lines that there is a black circle in the middle. Any idea?
I am using quadraticCurveTo now, but maybe bezier curve is a better option...
My full code:
var canvas = document.getElementById('myCanvas');
var color_arr = new Array("yellow","orange","OrangeRed","red","violetred","MediumSlateBlue","blue","aquamarine","green","greenyellow");
var sA = (Math.PI / 180) * 270;
var pA = (Math.PI / 180) * 36;
if (canvas && canvas.getContext) {
var ctx = canvas.getContext("2d");
if (ctx) {
ctx.fillStyle = "black";
ctx.fillRect(0,0,ctx.canvas.width, ctx.canvas.height);
for (var i=0; i <= 9; i++) {
ctx.strokeStyle = color_arr[i];
ctx.lineWidth = 5;
ctx.beginPath();
ctx.arc (350, 350, 250, sA+(i)*pA, sA+(i+1)*pA, false);
ctx.stroke();
ctx.closePath();
ctx.fillStyle = "white";
ctx.strokeStyle = "white";
ctx.font = "italic 30pt Arial";
if (i > 4 && i < 8) {
ctx.fillText(i.toString(), 350+290*Math.cos(sA+(i+0.5)*pA),350+290*Math.sin(sA+(i+0.5)*pA));
} else {
if (i == 3 || i == 4 || i == 8) {
ctx.fillText(i.toString(), 350+275*Math.cos(sA+(i+0.5)*pA),350+275*Math.sin(sA+(i+0.5)*pA));
} else {
ctx.fillText(i.toString(), 350+260*Math.cos(sA+(i+0.5)*pA),350+260*Math.sin(sA+(i+0.5)*pA));
}
}
}
var pi = '31415...';
for (i = 0; i <= 250; i++) {
line(parseInt(pi.substr(i,1)),parseInt(pi.substr(i+1,1)));
}
}
}
function line(no_1,no_2) {
var rand_1 = Math.random();
var rand_2 = Math.random();
var grad= ctx.createLinearGradient(350+250*Math.cos(sA+(no_1+rand_1)*pA), 350+250*Math.sin(sA+(no_1+rand_1)*pA), 350+250*Math.cos(sA+(no_2+rand_2)*pA), 350+250*Math.sin(sA+(no_2+rand_2)*pA));
grad.addColorStop(0, color_arr[no_1]);
grad.addColorStop(1, color_arr[no_2]);
ctx.lineWidth = 1;
ctx.strokeStyle = grad;
ctx.beginPath();
ctx.moveTo(350+250*Math.cos(sA+(no_1+rand_1)*pA), 350+250*Math.sin(sA+(no_1+rand_1)*pA));
ctx.quadraticCurveTo(350,350,350+250*Math.cos(sA+(no_2+rand_2)*pA),350+250*Math.sin(sA+(no_2+rand_2)*pA));
ctx.stroke();
}
Interesting!
The black circle in the middle is just an absence of curves.
The "lines" are cubic Bezier curves.
The beziers appear to be anchored on both ends to the circle circumference at intervals.
Here's my try at a simplified version of that PI: http://jsfiddle.net/m1erickson/Ju6E8/
This could be addictive so I'm leaving my attempt simple!
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:50px; }
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var PI2=Math.PI*2;
var cx=150;
var cy=150;
var r=100;
ctx.arc(cx,cy,r,0,Math.PI*2);
ctx.closePath();
ctx.stroke();
for(var a=0;a<PI2;a+=PI2/20){
ctx.strokeStyle="blue";
curve(a,PI2/2.5,25);
ctx.strokeStyle="green";
curve(a,PI2/5,50);
ctx.strokeStyle="red";
curve(a,PI2/10,75);
}
function curve(rotation,offset,innerRadius){
var x1=cx+r*Math.cos(rotation);
var y1=cy+r*Math.sin(rotation);
var x2=cx+innerRadius*Math.cos(rotation+offset/3.5);
var y2=cy+innerRadius*Math.sin(rotation+offset/3.5);
var x3=cx+innerRadius*Math.cos(rotation+offset/1.5);
var y3=cy+innerRadius*Math.sin(rotation+offset/1.5);
var x4=cx+r*Math.cos(rotation+offset);
var y4=cy+r*Math.sin(rotation+offset);
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.bezierCurveTo(x2,y2,x3,y3,x4,y4);
ctx.stroke();
}
$("#stop").click(function(){});
}); // end $(function(){});
</script>
</head>
<body>
<button id="stop">Stop</button><br>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
Hi all again i have problem in my chart construction in html 5. This time did everything well except one part or module. I tried some code which i got through internet for displaying some alert when a rectangle in canvas in clicked. When i comment the module it works fine but not the mouse click. Can anyone help me out. Thanks in advance. Here is my fiddle and code [fiddle]: http://jsfiddle.net/s8kZs/
<!doctype html>
<html>
<head>
<script type="text/javascript">
window.onload=function() {
var canvas=document.getElementById('mycanvas');
var ctx=canvas.getContext('2d');
var graphInfo=[{data:[120,130,140,160,180,100],color:'purple',label:["a","b","c","d","e","f"]},{data:[100,120,130,140,150,190],color:'green',label:["g","h","i","j","k","l"]}];
var width=45;
function renderGrid(gridPixelSize, color)
{
ctx.save();
ctx.lineWidth = 0.5;
ctx.strokeStyle = color;
for(var i = 20; i <= canvas.height-20; i = i + gridPixelSize)
{
ctx.beginPath();
ctx.moveTo(20, i);
ctx.lineTo(canvas.width-20, i);
ctx.closePath();
ctx.stroke();
}
for(var j = 20; j <= canvas.width-20; j = j + gridPixelSize)
{
ctx.beginPath();
ctx.moveTo(j, 20);
ctx.lineTo(j, canvas.height-20);
ctx.closePath();
ctx.stroke();
}
ctx.restore();
}
renderGrid(10, "grey");
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.moveTo(20, canvas.height-20);
ctx.lineTo(canvas.width-20, canvas.height-20);
ctx.closePath();
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.moveTo(20, 20);
ctx.lineTo(20, canvas.height-20);
ctx.closePath();
ctx.stroke();
ctx.font = "bold 16px Arial";
function getFunctionForTimeout(j){
var i=0,currx=30,info=graphInfo[j],x5=j*5;
var fTimeout=function(){
var h=Math.max(info.data[i]-x5,0);
var m=info.label[i];
ctx.fillStyle='black'
ctx.fillRect(currx+(10*x5)+2,canvas.height-h-20,width+2,h-1);
ctx.fillStyle=info.color;
ctx.fillRect(currx+(10*x5),canvas.height-h-21,width,h);
ctx.fillText(m, currx+(10*x5)+20, canvas.height-5);
currx+=120;
i++;
/*var ctx = $('#mycanvas').get(0).getContext('2d');
$('#mycanvas').click(function(e) {
var x = e.offsetX,
y = e.offsetY;
for(var k=0;k<j;k++) {
if(x > currx+(10*x5)
&& x < canvas.height-h-21
&& y > width
&& y < h) {
alert('Rectangle ' + j + ' clicked');
}
}
});*/
if(i<info.data.length)setTimeout(fTimeout,2000);
};
return fTimeout;
}
for(var j=graphInfo.length-1;j>=0;j--) {
setTimeout(getFunctionForTimeout(j),2000);
}
};
</script>
</head>
<body>
<canvas id="mycanvas" height="400" width="800" style="border:1px solid #000000;">
</body>
</html>
Here is the code for giving you mouse position where you are clicking on the canvas, i just altered your code for correcting it for the alert you are expecting but there is some issue in your condition which you generate as an alert.
Njoy clicking and alerting the mouse position; if you want the same alert you expect, alter your if condition you will get it by my position alert...
<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
window.onload=function() {
var canvas=document.getElementById('mycanvas');
var ctx=canvas.getContext('2d');
var graphInfo=[{data:[120,130,140,160,180,100],color:'purple',label:["a","b","c","d","e","f"]},{data:[100,120,130,140,150,190],color:'green',label:["g","h","i","j","k","l"]}];
var width=45;
function renderGrid(gridPixelSize, color)
{
ctx.save();
ctx.lineWidth = 0.5;
ctx.strokeStyle = color;
for(var i = 20; i <= canvas.height-20; i = i + gridPixelSize)
{
ctx.beginPath();
ctx.moveTo(20, i);
ctx.lineTo(canvas.width-20, i);
ctx.closePath();
ctx.stroke();
}
for(var j = 20; j <= canvas.width-20; j = j + gridPixelSize)
{
ctx.beginPath();
ctx.moveTo(j, 20);
ctx.lineTo(j, canvas.height-20);
ctx.closePath();
ctx.stroke();
}
ctx.restore();
}
renderGrid(10, "grey");
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.moveTo(20, canvas.height-20);
ctx.lineTo(canvas.width-20, canvas.height-20);
ctx.closePath();
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.moveTo(20, 20);
ctx.lineTo(20, canvas.height-20);
ctx.closePath();
ctx.stroke();
ctx.font = "bold 16px Arial";
function getFunctionForTimeout(j){
var i=0,currx=30,info=graphInfo[j],x5=j*5;
var fTimeout=function(){
var h=Math.max(info.data[i]-x5,0);
var m=info.label[i];
var ctx = $('#mycanvas').get(0).getContext('2d');
ctx.fillStyle='black'
ctx.fillRect(currx+(10*x5)+2,canvas.height-h-20,width+2,h-1);
ctx.fillStyle=info.color;
ctx.fillRect(currx+(10*x5),canvas.height-h-21,width,h);
ctx.fillText(m, currx+(10*x5)+20, canvas.height-5);
currx+=120;
i++;
$('#mycanvas').click(function(e) {
var canvas = document.getElementById("myCanvas");
var mousePos = getMousePos(canvas, e);
var message = "Mouse position: " + mousePos.x + "," + mousePos.y;
var x = mousePos.x;
var y = mousePos.y;
alert(message);
for(var k=0;k<j;k++) {
if(x > currx+(10*x5)
&& x < canvas.height-h-21
&& y > width
&& y < h) {
alert('Rectangle ' + j + ' clicked');
}
}
});
if(i<info.data.length)setTimeout(fTimeout,2000);
};
return fTimeout;
}
for(var j=graphInfo.length-1;j>=0;j--) {
setTimeout(getFunctionForTimeout(j),2000);
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect(), root = document.documentElement;
// return relative mouse position
var mouseX = evt.clientX - rect.top - root.scrollTop;
var mouseY = evt.clientY - rect.left - root.scrollLeft;
return {
x: mouseX,
y: mouseY
};
}
};
</script>
</head>
<body>
<canvas id="mycanvas" height="400" width="800" style="border:1px solid #000000;">
</body>
</html>
Just check the change in getMousePos() for the same u needed
Cheers!!! Njoy!!!