Code works in jsfiddle and but not in the Browser - javascript

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>

Related

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>

Why is my code working on jsfiddle but not my HTML file

I am using jsfiddle to store some coordinates. The coordinates gets displayed on jsfiddle but when I copy it on my local files the coordinates don't get displayed.
I would like to display the coordinates of that line on my local files, How can this be done?
This is my HTML file
<canvas id="canvas" width="300" height="300" style="border: 1px solid black;"> </canvas>
<div id="coord"></div>
<div id="coords"></div>
This is my Javascript File
var canvas = document.getElementById('canvas'),
coord = document.getElementById('coord'),
ctx = canvas.getContext('2d'), // get 2D context
imgCat = new Image(),
arr = [];
imgCat.src = ''http://c.wearehugh.com/dih5/openclipart.org_media_files_johnny_automatic_1360.png';
imgCat.onload = function() { // wait for image load
ctx.drawImage(imgCat, 0, 0); // draw imgCat on (0, 0)
};
var mousedown = false;
ctx.strokeStyle = '#0000FF';
ctx.lineWidth = 5;
canvas.onmousedown = function(e) {
arr = [];
var pos = fixPosition(e, canvas);
mousedown = true;
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
return false;
};
canvas.onmousemove = function(e) {
var pos = fixPosition(e, canvas);
coord.innerHTML = '(' + pos.x + ',' + pos.y + ')';
if (mousedown) {
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
arr.push([pos.x, pos.y])
}
};
canvas.onmouseup = function(e) {
mousedown = false;
$('#coords').html(JSON.stringify(arr, null, 2));
};
function fixPosition(e, gCanvasElement) {
var x;
var y;
if (e.pageX || e.pageY) {
x = e.pageX;
y = e.pageY;
}
else {
x = e.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
x -= gCanvasElement.offsetLeft;
y -= gCanvasElement.offsetTop;
return {x: x, y:y};
}
Demo Here
Copy this in a html page. The probleme was your link imgCat.src = ''http://c.wearehugh.com/dih5/openclipart.org_media_files_johnny_automatic_1360.png';
You put two ''
<html>
<canvas id="canvas" width="300" height="300" style="border: 1px solid black;"></canvas>
<div id="coord"></div>
<div id="coords"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js</script>
</html>
<script type="text/javascript">
var canvas = document.getElementById('canvas'),
coord = document.getElementById('coord'),
ctx = canvas.getContext('2d'), // get 2D context
imgCat = new Image(),
arr = [];
imgCat.src ='http://www.clipartbest.com/cliparts/bTy/E5x/bTyE5xLjc.png';
imgCat.onload = function() { // wait for image load
ctx.drawImage(imgCat, 0, 0); // draw imgCat on (0, 0)
};
var mousedown = false;
ctx.strokeStyle = '#0000FF';
ctx.lineWidth = 5;
canvas.onmousedown = function(e) {
arr = [];
var pos = fixPosition(e, canvas);
mousedown = true;
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
return false;
};
canvas.onmousemove = function(e) {
var pos = fixPosition(e, canvas);
coord.innerHTML = '(' + pos.x + ',' + pos.y + ')';
if (mousedown) {
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
arr.push([pos.x, pos.y])
}
};
canvas.onmouseup = function(e) {
mousedown = false;
$('#coords').html(JSON.stringify(arr, null, 2));
};
function fixPosition(e, gCanvasElement) {
var x;
var y;
if (e.pageX || e.pageY) {
x = e.pageX;
y = e.pageY;
}
else {
x = e.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
x -= gCanvasElement.offsetLeft;
y -= gCanvasElement.offsetTop;
return {x: x, y:y};
}
</script>
some configuration is applying to jsfiddle automatically and you need to apply them by your hands.
first you need to add jQuery to you site. Add this line between <head> </head> tags:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
second you need to check that you script executes for example when page loads. you need to put you code into this:
$(function() {
// You script here
});
or put it just before </body> tag
so in output you jquery code will be like this:
<script>
$(function() {
var canvas = document.getElementById('canvas'),
coord = document.getElementById('coord'),
ctx = canvas.getContext('2d'), // get 2D context
imgCat = new Image(),
arr = [];
imgCat.src = ''http://c.wearehugh.com/dih5/openclipart.org_media_files_johnny_automatic_1360.png';
imgCat.onload = function() { // wait for image load
ctx.drawImage(imgCat, 0, 0); // draw imgCat on (0, 0)
};
var mousedown = false;
ctx.strokeStyle = '#0000FF';
ctx.lineWidth = 5;
canvas.onmousedown = function(e) {
arr = [];
var pos = fixPosition(e, canvas);
mousedown = true;
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
return false;
};
canvas.onmousemove = function(e) {
var pos = fixPosition(e, canvas);
coord.innerHTML = '(' + pos.x + ',' + pos.y + ')';
if (mousedown) {
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
arr.push([pos.x, pos.y])
}
};
canvas.onmouseup = function(e) {
mousedown = false;
$('#coords').html(JSON.stringify(arr, null, 2));
};
function fixPosition(e, gCanvasElement) {
var x;
var y;
if (e.pageX || e.pageY) {
x = e.pageX;
y = e.pageY;
}
else {
x = e.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
x -= gCanvasElement.offsetLeft;
y -= gCanvasElement.offsetTop;
return {x: x, y:y};
}
});
</script>
1.Check the doc type of the HTML :should be html for (HTML 5)or no doc type
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2.Make sure your scripts are getting loaded properly.
Check the path of Jquery script.
--Externally downloaded scripts need to be unblocked
(Righ Click -> Properties -> (General Tab)'Unblock' Option on bottom)
(Right Click -> Properties -> (general Tab) -> Advanced -> Uncheck Encrypt option if checked.)
3.Put your code inside a function.
(Specifically the binding related codes.)
Other functions need to be defined outside document ready.(Already done)
And Call that function inside document ready.
$(document).ready(function () {
DrawImage();
});
function DrawImage()
{
//your code here
var canvas = document.getElementById('canvas'),
coord = document.getElementById('coord'),
ctx = canvas.getContext('2d'), // get 2D context
imgCat = new Image(),
arr = [];
/*********** draw image *************/
imgCat.src = 'http://c.wearehugh.com/dih5/openclipart.org_media_files_johnny_automatic_1360.png';
imgCat.onload = function() { // wait for image load
ctx.drawImage(imgCat, 0, 0); // draw imgCat on (0, 0)
};
/*********** handle mouse events on canvas **************/
var mousedown = false;
ctx.strokeStyle = '#0000FF';
ctx.lineWidth = 5;
canvas.onmousedown = function(e) {
arr = [];
var pos = fixPosition(e, canvas);
mousedown = true;
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
return false;
};
canvas.onmousemove = function(e) {
var pos = fixPosition(e, canvas);
coord.innerHTML = '(' + pos.x + ',' + pos.y + ')';
if (mousedown) {
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
arr.push([pos.x, pos.y])
}
};
canvas.onmouseup = function(e) {
mousedown = false;
$('#coords').html(JSON.stringify(arr, null, 2));
};
}
//Utils
function fixPosition(e, gCanvasElement) {
//put codes of this function here.
}
just add your script before end of body tag and your problem will solve.

How to specify different locations for mousemove to trigger?

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);
});

how to remove a unconnected points when i mouseout from canvas

i need to remove unconnected points when i mouseout from canvas. I just draw lines when mousemove using moveTo and LineTo. when mouseout from canvas have to omit the unconnected points.
Here is code for jquery:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(function() {
var canvas = $('#canvas');
var context = canvas.get(0).getContext("2d");
var clicked = false;
var b=0;
var storedLines = [];
var storedLine = {};
var mouse = {
x: -1,
y: -1
}
var parentOffset = $('#canvas').offset();
canvas.click(function(e) {
if (b==1)
{
$(this).unbind(e);
}
else
{
clicked = true;
mouse.x = e.pageX - parentOffset.left;
mouse.y = e.pageY - parentOffset.top;
context.moveTo(mouse.x, mouse.y);
if (clicked) {
storedLines.push({
startX: storedLine.startX,
startY: storedLine.startY,
endX: mouse.x,
endY: mouse.y
});
}
storedLine.startX = mouse.x;
storedLine.startY = mouse.y;
$(this).mousemove(function(k) {
context.clearRect(0, 0, 960, 500);
context.beginPath();
context.strokeStyle = "blue";
for (var i = 0; i < storedLines.length; i++) {
var v = storedLines[i];
context.moveTo(v.startX, v.startY);
context.lineTo(v.endX, v.endY);
context.stroke();
}
context.moveTo(mouse.x, mouse.y);
context.lineTo(k.pageX - parentOffset.left, k.pageY - parentOffset.top);
context.stroke();
context.closePath();
});
}
});
$('#canvas').mouseout(function(e){
$(this).unbind("mousemove");
b=1;
});
});
HTML code:
<html>
<body>
<canvas id="canvas" width=600 height=600 ></canvas>
</body>
</html>
First thing to do is to clarify the code : Have one part that deals only with the mouse, and another part that deals only with the lines.
This way you will have a much better view on what will happen on each event.
I started a bit to clarify the code, you should even make a class handling lines (which will be very useful if you handle several of them).
jsbin is here : http://jsbin.com/eseTODo/2/edit?js,output
var canvas = $('#canvas');
var context = canvas.get(0).getContext("2d");
// -----------------------------------------
// Mouse
var clicked = false;
var onCanvas = false;
var mouse = {
x: -1,
y: -1
}
var parentOffset = $('#canvas').offset();
canvas.mousedown(function (e) {
clicked = true;
if (!onCanvas) return;
mouse.x = e.pageX - parentOffset.left;
mouse.y = e.pageY - parentOffset.top;
addPoint(mouse.x, mouse.y);
clearScreen();
drawLines();
});
canvas.mouseup(function (e) {
clicked = false;
if (!onCanvas) return;
});
canvas.mousemove(function (e) {
if (!onCanvas) return;
clearScreen();
drawLines();
drawPendingLine(e.pageX - parentOffset.left,
e.pageY - parentOffset.top);
});
canvas.mouseout(function (e) {
onCanvas = false;
clearScreen();
drawLines();
clearLines();
});
canvas.mouseenter(function (e) {
onCanvas = true;
});
// -----------------------------------------
// Lines
var storedLines = [];
var storedLine = {};
var startedALine = false;
function clearLines() {
storedLines.length = 0;
startedALine = false;
}
function addPoint(x, y) {
if (startedALine) {
storedLines.push({
startX: storedLine.startX,
startY: storedLine.startY,
endX: x,
endY: y
});
}
startedALine = true;
storedLine.startX = x;
storedLine.startY = y
}
function drawLines() {
context.strokeStyle = "blue";
if (!startedALine) return;
if (!storedLines.length) return;
for (var i = 0; i < storedLines.length; i++) {
var v = storedLines[i];
context.beginPath();
context.moveTo(v.startX, v.startY);
context.lineTo(v.endX, v.endY);
context.stroke();
context.closePath();
}
context.stroke();
}
function drawPendingLine(lastX, lastY) {
if (!startedALine) return;
context.beginPath();
context.strokeStyle = "green";
context.moveTo(storedLine.startX, storedLine.startY);
context.lineTo(lastX, lastY);
context.stroke();
context.closePath();
}
function clearScreen() {
context.clearRect(0, 0, 600, 600);
}
Can't you set a flag like
var hasLeftCanvas = false;
and set it to true when you leave the canvas?
canvas.onmouseleave = function() {
hasLeftCanvas = true;
}
and then, in your script:
$(this).mousemove(function(k) {
if(!hasLeftCanvas) {
context.clearRect(0, 0, 960, 500);
context.beginPath();
context.strokeStyle = "blue";
for (var i = 0; i < storedLines.length; i++) {
var v = storedLines[i];
context.moveTo(v.startX, v.startY);
context.lineTo(v.endX, v.endY);
context.stroke();
}
context.moveTo(mouse.x, mouse.y);
context.lineTo(k.pageX - parentOffset.left, k.pageY - parentOffset.top);
context.stroke();
context.closePath();
}
});
remember to set it back to false when the cursor re enters the canvas

Categories