How to specify different locations for mousemove to trigger? - javascript

the code
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<style>
body {
background-color:#E4E0FF;
}
#canvas {
border:10px solid red;
background-color:white;
}
#canvas1 {
border:10px solid red;
background-color:white;
}
#canvas2 {
border:10px solid red;
background-color:white;
}
</style>
</head>
<body>
<h1>My canvas Art Gallery</h1>
<canvas id="canvas" width="400" height="300">
</canvas>
<canvas id="canvas1" width="400" height="300">
</canvas>
<canvas id="canvas2" 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 changeRadius;
var changeWidth;
var isDown = false;
var startX;
var startY;
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 () {
var c1 = document.getElementById("canvas1");
var ctx = c1.getContext("2d");
var $canvas = $("#canvas1");
var toggle = 0;
var x = 150;
var y = 100;
var w = 100;
var h = 100;
var r = 60;
var wasInside = false;
ctx.beginPath();
ctx.arc(200, 150, r, 0, 2 * Math.PI);
ctx.stroke();
changeRadius = 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 () {
var c = document.getElementById("canvas2");
var ctx = c.getContext("2d");
var $canvas = $("#canvas2");
var toggle = 0;
var x = 150;
var y = 100;
var w = 100;
var h = 100;
var width = 2;
var wasInside = false;
ctx.lineWidth = width;
ctx.moveTo(150,100);
ctx.lineTo(250,200);
ctx.stroke();
changeWidth = 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, canv) {
console.log(canv);
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) {
switch(canv.id){
case 'canvas':
changeColor();
break;
case 'canvas1' :
changeRadius();
break;
case 'canvas2':
changeWidth();
break;
}
wasInside = true;
} else if (!isInsideNow && wasInside) {
wasInside = false;
}
}
$("#canvas, #canvas1, #canvas2").mousemove(function (e) {
handleMouseMove(e,this);
});
</script>
</body>
</html>
Aim is to change the color in first, circle size in second and width of line in third canvas.
So, the problem is the location defined by x, y, w and h is in the first canvas and I can't get the any reaction from 2nd and 3rd canvas by the mouse. Here's the fiddle
http://jsfiddle.net/x5xH5/23/
how can I solve this??

Here I could get it working using .mouseenter and removing those many isInsides and others, though I am not sure if it satisfies your requirements:
DEMO
What I changed:
// Just the last few lines
function handleMouseMove(e, canv) {
console.log(canv);
switch(canv.id){
case 'canvas':
changeColor();
break;
case 'canvas1' :
changeRadius();
break;
case 'canvas2':
changeWidth();
break;
}
}
$("#canvas, #canvas1, #canvas2").mouseenter(function (e) {
handleMouseMove(e, this);
});

Related

Stopping a object in java script canvas at specific point

I have created a circle and make it move on X axis in canvas. And I manage to stop for a few second at specific point and turn it's path on Y axis.
Now I want to make it stop for a few seconds at some point in Y axis, and return to the point where it started on Y axis journey.
I've tried multiple ways and it want work for me. I would really thankful if someone can help on this.
Java Script(Demo2.js)
window.onload = init();
function init() {
c = document.getElementById("canvas1");
ctx = c.getContext('2d');
ctx.fillStyle = "white";
ctx.rect(0, 0, 800, 500);
ctx.fill();
var x1 = 50;
var y1 = 150;
var SPEED = 2;
var goRight = true;
var count = 0;
var stop = false;
function updateStuff() {
if (goRight == true && stop == false)
x1 = x1 + SPEED;
//if(x1 > 1000)
//SPEED = SPEED * -1;
//if(x1 < 1)
//SPEED = SPEED * -1;
if (count > 200)
stop = true;
if (count > 300) {
stop = false;
goRight = false;
}
if (goRight == false && stop == false) {
y1 = y1 + 1;
}
function clear() {
ctx.fillStyle = "white";
ctx.rect(0, 0, 800, 500);
ctx.fill();
}
function drawStuff() {
ctx.beginPath();
ctx.arc(x1, y1, 50, 0, 2 * Math.PI, false);
ctx.fillStyle = "RED";
ctx.fill();
}
function gameLoop() {
count = count + 1;
clear();
updateStuff();
drawStuff();
setTimeout(gameLoop, 20)
}
gameLoop();
}
}
<canvas id="canvas1" width="800" height="500"></canvas>

Drawing a straight line using mouse events on canvas in javascript

I am trying to draw a straight line on canvas using mouse events.I am new to java script. Can anybody help or refer something from where i can get help?
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
position: absolute;
margin: auto;
left: 0;
right: 0;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var bounds = null;
var ctx = null;
var hasLoaded = false;
var startX = 0;
var startY = 0;
var mouseX = 0;
var mouseY = 0;
var isDrawing = false;
var existingLines = [];
function draw() {
ctx.fillStyle = "#333333";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
ctx.beginPath();
for (var i = 0; i < existingLines.length; ++i) {
var line = existingLines[i];
ctx.moveTo(line.startX,line.startY);
ctx.lineTo(line.endX,line.endY);
}
ctx.stroke();
if (isDrawing) {
ctx.strokeStyle = "darkred";
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(startX,startY);
ctx.lineTo(mouseX,mouseY);
ctx.stroke();
}
}
function onmousedown(e) {
if (hasLoaded && e.button === 0) {
if (!isDrawing) {
startX = e.clientX - bounds.left;
startY = e.clientY - bounds.top;
isDrawing = true;
}
draw();
}
}
function onmouseup(e) {
if (hasLoaded && e.button === 0) {
if (isDrawing) {
existingLines.push({
startX: startX,
startY: startY,
endX: mouseX,
endY: mouseY
});
isDrawing = false;
}
draw();
}
}
function onmousemove(e) {
if (hasLoaded) {
mouseX = e.clientX - bounds.left;
mouseY = e.clientY - bounds.top;
if (isDrawing) {
draw();
}
}
}
window.onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
canvas.onmousedown = onmousedown;
canvas.onmouseup = onmouseup;
canvas.onmousemove = onmousemove;
bounds = canvas.getBoundingClientRect();
ctx = canvas.getContext("2d");
hasLoaded = true;
draw();
}
</script>
</body>
</html>

Bullet Hell Design Tips

Ok, so i'm very new to javascript, and i'm just making my first non-tutorial game, just a simple bullethell thing. I made it so that bullets randomly fly from the walls, but it only does that once. I want it to fire the bullets from a random place, wait about 1 second, then fire 4 more bullets from other random places. THANK YOU IN ADVANCE!
Heres the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Square</title>
<style>
* { padding: 0; margin: 0; }
canvas { background: #eee; display: block; margin: 0 auto; }
</style>
</head>
<body>
<canvas id="myCanvas" width="480" height="320"></canvas>
<fom name="Show">
<input type="text" name="MouseX" value="0" size="4"> X<br>
<input type="text" name="MouseY" value="0" size="4"> Y<br>
</form>
<script language="JavaScript1.2">
var canvas=document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x=canvas.width/2;
var y=canvas.height-30;
var playerHeight = 20;
var playerWidth = 20;
var enemyHeight = 10;
var enemyWidth = 10;
var IE = document.all?true:false
var randRight = Math.random()*320;
var randLeft = Math.random()*320;
var randTop = Math.random()*320;
var randBottom = Math.random()*320;
var enemyXPosRight = 480;
var enemyXPosLeft = 0;
var enemyYPosTop = 0;
var enemyYPosBottom = 320;
var rep = true;
if (!IE) document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = getMouseXY;
var tempX = 0
var tempY = 0
// Main function to retrieve mouse x-y pos.s
function getMouseXY(e) {
if (IE) {
tempX = event.clientX + document.body.scrollLeft
tempY = event.clientY + document.body.scrollTop
} else {
tempX = e.pageX
tempY = e.pageY
}
if (tempX < 0){tempX = 0}
if (tempY < 0){tempY = 0}
document.Show.MouseX.value = tempX
document.Show.MouseY.value = tempY
return true
}
function drawPlayer() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.rect(tempX-500, tempY-20, playerWidth, playerHeight);
ctx.fill();
ctx.closePath();
if (tempX < 500) {
tempX = 500;
}
if (tempX > 960) {
tempX = 960;
}
if (tempY < 38) {
tempY = 38;
}
if (tempY > 340) {
tempY = 340;
}
}
function drawEnemyRight() {
ctx.beginPath();
ctx.rect(enemyXPosRight-=3, randRight, enemyWidth, enemyHeight);
ctx.fill();
ctx.closePath();
}
function drawEnemyLeft() {
ctx.beginPath();
ctx.rect(enemyXPosLeft+=3, randLeft, enemyWidth, enemyHeight);
ctx.fill();
ctx.closePath();
}
function drawEnemyTop() {
ctx.beginPath();
ctx.rect(randTop, enemyYPosTop+=3, enemyWidth, enemyHeight);
ctx.fill();
ctx.closePath();
}
function drawEnemyBottom() {
ctx.beginPath();
ctx.rect(randBottom, enemyYPosBottom-=3, enemyWidth, enemyHeight);
ctx.fill();
ctx.closePath();
}
function draw() {
drawPlayer();
drawEnemyBottom();
drawEnemyRight();
drawEnemyLeft();
drawEnemyTop();
requestAnimationFrame(draw);
}
draw();
</script>
</body>
</html>

HTML5 and canvas to plot Pie Chart

I'm trying to plot a pie chart using HTML5 and Canvas.
Here below is my working example in jsfiddle.
http://jsfiddle.net/2mf8gt2c/
I need to show the values inside of the pie chart.
i.e
var myColor = ["Green","Red","Blue"];
var myData = [30,60,10];
The value should be displayed inside the pie chart. How can I achieve that?
The full code is available below.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>My Title</title>
</head>
<body>
<section>
<div>
<table width="80%" cellpadding=1 cellspacing=1 border=0>
<tr>
<td width=50%><canvas id="canvas" align="center" width="400" height="250"> This text is displayed if your browser does not support HTML5 Canvas. </canvas>
</td>
</tr>
</table>
</div>
<script type="text/javascript">
var myColor = ["Green","Red","Blue"];
var myData = [30,60,10];
function degreesToRadians(degrees) {
return (degrees * Math.PI)/180;
}
function sumTo(a, i) {
var sum = 0;
for (var j = 0; j < i; j++) {
sum += a[j];
}
return sum;
}
function getTotal(){
var myTotal = 0;
for (var j = 0; j < myData.length; j++) {
myTotal += (typeof myData[j] == 'number') ? myData[j] : 0;
}
return myTotal;
}
var drawSegmentLabel = function(canvas, context, i)
{
context.save();
var x = Math.floor(250 / 2);
var y = Math.floor(100 / 2);
var angle;
var angleD = sumTo(myData, i);
var flip = (angleD < 90 || angleD > 270) ? false : true;
context.translate(x, y);
if (flip) {
angleD = angleD-180;
context.textAlign = "left";
angle = degreesToRadians(angleD);
context.rotate(angle);
context.translate(-(x + (canvas.width * 0.5))+15, -(canvas.height * 0.05)-10);
}
else {
context.textAlign = "right";
angle = degreesToRadians(angleD);
context.rotate(angle);
}
var fontSize = Math.floor(canvas.height / 25);
context.font = fontSize + "pt Helvetica";
context.fillStyle = "black";
var dx = Math.floor(250 * 0.5) - 10;
var dy = Math.floor(100 * 0.05);
context.fillText(myData[i], dx, dy);
context.restore();
}
function plotData()
{
var canvas;
var ctx;
var lastend = 0;
var myTotal = getTotal();
var pRadius = 100;
var xPie=250;
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.imageSmoothingEnabled = true;
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < myData.length; i++)
{
ctx.fillStyle = myColor[i];
ctx.beginPath();
ctx.moveTo(xPie,pRadius+10);
ctx.arc(xPie,pRadius+10,pRadius,lastend,lastend +
(Math.PI*2*(myData[i]/myTotal)),false);
ctx.lineTo(xPie,pRadius+10);
ctx.fill();
lastend += Math.PI*2*(myData[i]/myTotal);
ctx.lineWidth = 2;
ctx.strokeStyle = '#000000';
ctx.stroke();
}
}
plotData();
</script>
</section>
</body>
</html>
Can someone help me to get this done?
Thanks,
Kimz
Here's an alternate way to draw a wedge with a specified starting & ending angle:
ctx.beginPath();
ctx.moveTo(cx,cy);
ctx.arc(cx,cy,radius,startAngle,endAngle,false);
ctx.closePath();
ctx.fillStyle=fill;
ctx.strokeStyle='black';
ctx.fill();
ctx.stroke();
I suggest this alternate method because you can easily calculate the angle exactly between the starting & ending angle like this:
var midAngle=startAngle+(endAngle-startAngle)/2;
And given the midAngle, you can use some trigonometry to calculate where to draw your values inside the wedge:
// draw the value labels 75% of the way from centerpoint to
// the outside of the wedge
var labelRadius=radius*.75;
// calculate the x,y at midAngle
var x=cx+(labelRadius)*Math.cos(midAngle);
var y=cy+(labelRadius)*Math.sin(midAngle);
Here's example code and a Demo:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
ctx.lineWidth = 2;
ctx.font = '12px verdana';
var PI2 = Math.PI * 2;
var myColor = ["Green", "Red", "Blue"];
var myData = [30, 60, 10];
var cx = 150;
var cy = 150;
var radius = 100;
pieChart(myData, myColor);
function pieChart(data, colors) {
var total = 0;
for (var i = 0; i < data.length; i++) {
total += data[i];
}
var sweeps = []
for (var i = 0; i < data.length; i++) {
sweeps.push(data[i] / total * PI2);
}
var accumAngle = 0;
for (var i = 0; i < sweeps.length; i++) {
drawWedge(accumAngle, accumAngle + sweeps[i], colors[i], data[i]);
accumAngle += sweeps[i];
}
}
function drawWedge(startAngle, endAngle, fill, label) {
// draw the wedge
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.arc(cx, cy, radius, startAngle, endAngle, false);
ctx.closePath();
ctx.fillStyle = fill;
ctx.strokeStyle = 'black';
ctx.fill();
ctx.stroke();
// draw the label
var midAngle = startAngle + (endAngle - startAngle) / 2;
var labelRadius = radius * .75;
var x = cx + (labelRadius) * Math.cos(midAngle);
var y = cy + (labelRadius) * Math.sin(midAngle);
ctx.fillStyle = 'white';
ctx.fillText(label, x, y);
}
body {
background-color: ivory;
padding: 10px;
}
#canvas {
border: 1px solid red;
}
<canvas id="canvas" width=400 height=300></canvas>

Code works in jsfiddle and but not in the Browser

Here is my HTML5 code. whenever I try to run this file i am getting a black canvas with no rectangle inside. But it is working perfectly as flawlessly in the jsfiddle.
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<style>
body {
background-color:ivory;
}
#canvas {
border:10px solid red;
background-color:black;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="300">
</canvas>
<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 isDown = false;
var startX;
var startY;
var toggle=0;
var x=150;
var y=100;
var w=100;
var h=100;
var wasInside=false;
ctx.fillStyle = "#04B45F";
ctx.fillRect(x, y, w, h);
function changeColor() {
if (toggle == 0) {
ctx.fillStyle = "#FFFFFF";
toggle = 1;
} else {
ctx.fillStyle = "#04B45F";
toggle = 0;
}
ctx.fillRect(x, y, w, h);
}
function handleMouseMove(e) {
e.preventDefault();
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);
});
</script>
</body>
</html>
And here's the link to jsfiddle http://jsfiddle.net/9GcbH/4/. I am using the exact code in my system. But it is not working for me. May i know the exact reason and how to overcome it ?
you neeed to include js script inside head tag from remote CDN or from your local
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
You need to wrap your jQuery code inside DOM ready handler $(function() {...});.
This task has been done by jsFiddle automatically when you've included jQuery.
$(function() {
$("#canvas").mousemove(function (e) {
handleMouseMove(e);
});
});
Actually you're missing jQuery library in your code, so you need to include it. So you can do:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(function() {
$("#canvas").mousemove(function (e) {
handleMouseMove(e);
});
});
</script>
And put above code at the bottom of your page before closing </body> tag.
Try this
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<style>
body {
background-color:ivory;
}
#canvas {
border:10px solid red;
background-color:black;
}
</style>
</head>
<body>
<canvas id="canvas" 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 isDown = false;
var startX;
var startY;
var toggle=0;
var x=150;
var y=100;
var w=100;
var h=100;
var wasInside=false;
ctx.fillStyle = "#04B45F";
ctx.fillRect(x, y, w, h);
function changeColor() {
if (toggle == 0) {
ctx.fillStyle = "#FFFFFF";
toggle = 1;
} else {
ctx.fillStyle = "#04B45F";
toggle = 0;
}
ctx.fillRect(x, y, w, h);
}
function handleMouseMove(e) {
e.preventDefault();
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);
});
</script>
</body>
</html>

Categories