I am trying to write some JavaScript that draws a line by dragging the mouse, and then removes it when you let go of left click.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload = function() {
window.stop = false
window.canvas = document.getElementById("e");
window.context = canvas.getContext("2d");
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
window.pos = Shift();
}
function Shift() {
e = window.event
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop;
+ document.documentElement.scrollTop;
}
posx -= document.getElementById('e').offsetLeft;
posy -= document.getElementById('e').offsetTop;
return[posx,posy];
}
function up(){
document.getElementById('e').onmousemove = null;
canvas.width = canvas.width;
}
function mov(){
canvas.width = canvas.width;
window.pos = Shift();
context.moveTo(window.start[0],window.start[1]);
context.lineTo(pos[0],pos[1]);
context.stroke();
}
function down(){
window.start = Shift();
document.getElementById('e').onmousemove = "mov()";
}
</script>
</head>
<body>
<canvas id="e" onMouseDown="down()" onmousemove="" onMouseup="up()"></canvas>
</body>
</html>
This example does not work and throws no errors. If
document.getElementById('e').onmousemove = "mov()";
is commented out and onmousemove is set to
onmousemove="mov()"
then it works, but obviously a line can only be drawn once. Also neither of the examples worked in FireFox. Tested in Chrome.
Change this:
document.getElementById('e').onmousemove = "mov()";
To this:
document.getElementById('e').onmousemove = mov;
You want to assign .onmousemove to a function reference, not to a string. Note that there are no parentheses: if you assign ...onmousemove = mov() it will run the mov() function and assign onmousemove to the return from the function (undefined, with this particular function). Without the parentheses it assigns it to the function itself.
use
document.getElementById('e').addEventListener('mousemove', mov, false);
document.getElementById('e').removeEventListener('mousemove', mov);
Made some fixes, but it is crazy code :)
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload = function() {
window.stop = false
window.canvas = document.getElementById("e");
window.context = canvas.getContext("2d");
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
}
function Shift(e) {
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop;
+ document.documentElement.scrollTop;
}
posx -= document.getElementById('e').offsetLeft;
posy -= document.getElementById('e').offsetTop;
return[posx,posy];
}
function up(){
document.getElementById('e').removeEventListener('mousemove', mov);
canvas.width = canvas.width;
}
function mov(e){
canvas.width = canvas.width;
window.pos = Shift(e);
context.moveTo(window.start[0],window.start[1]);
context.lineTo(pos[0],pos[1]);
context.stroke();
}
function down(e){
window.start = Shift(e);
document.getElementById('e').addEventListener('mousemove', mov, false);
}
</script>
</head>
<body>
<canvas id="e" onMouseDown="down()" onmousemove="" onMouseup="up()"></canvas>
</body>
</html>
You're assigning the function incorrectly
http://jsfiddle.net/wmTYr/
<div id="meh">hi</div>
<script>
function go() {
alert();
}
document.getElementById("meh").onmouseover = go
</script>
Related
So I am new to javascript and a beginner programmer. I know the initialization subroutine always go first. I don't get why the subroutines aren't running. And I was wondering if any variables in the initialization subroutine can be used in any other subroutines. I am trying to make a program using Bresenham Line Algorithm.
<html>
<head>
<body>
<canvas id="canvas" width="500" height="500" style="border: 1px solid black;" onclick="coordinates(event)">></canvas>
</body>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
intialization();
drawGrid();
mouseClick();
//Intialization--------------------------------
//Intialization--------------------------------
function intialization() {
var cnv = document.getElementById("canvas");
var Width = cnv.width;
var Height = cnv.height;
var ctx = cnv.getContext('2d');
var click_counter = 0; //switching between storing first and second point coordinates
p1x = 0; //stores user's click on canvas
p1y = 0; //stores user's click on canvas
p2x = 0; //stores user's click on canvas
p2y = 0; //stores user's click on canvas
}
//Intialization--------------------------------
//GRID---------------------------------
function drawGrid() {
var gridLines = {
Lines: {
space: 10,
// color: "'#xxxxxx'"
}
};
drawGridLines(cnv, gridLines.Lines);
return;
}
function drawGridLines(cnv, lineOptions) {
ctx.strokeStyle = lineOptions.color;
ctx.strokeWidth = 1;
ctx.beginPath();
var counter = null;
var i = null;
var x = null;
var y = null;
counter = Math.floor(Width / lineOptions.space);
for (i = 1; i <= counter; i++) {
x = (i * lineOptions.space);
ctx.moveTo(x, 0);
ctx.lineTo(x, Height);
ctx.stroke();
}
counter = Math.floor(Height / lineOptions.space);
for (i = 1; i <= counter; i++) {
y = (i * lineOptions.space);
ctx.moveTo(0, y);
ctx.lineTo(Width, y);
ctx.stroke();
}
ctx.closePath();
return;
}
//GRID---------------------------------
//MOUSE---------------------------------
function mouseClick {
if (click_counter = 0) {
function coordinates(event) {
var x1 = event.offsetX;
var y1 = event.offsetY;
p1x = x1;
p1y = y1;
console.log("x coords: " + p1x + ", y coords: " + p1y);
} else
function coordinates(event) {
var x1 = event.offsetX;
var y1 = event.offsetY;
p2x = x1;
p2y = y1;
console.log("x coords: " + p2x + ", y coords: " + p2y);
}
}
//MOUSE---------------------------------
//MOUSE---------------------------------
</script>
</head>
</html>
Your initialization and drawGrid functions are being called before the document is even loaded so this will fail. You should use the jquery method-
$(document).ready(function(){
//callyour functions here
})
Another issue you have is that you are trying to use variables which are out of scope. Like cnv for example. You should declare a object like canvas at the top of your js:
canvas = {}
and add all of the variables you want to share to this. for instance :
canvas.cnv = document.getElementById("canvas");
canvas.Width = canvas.cnv.width;
canvas.Height = canvas.cnv.height;
canvas.ctx = canvas.cnv.getContext('2d');
Here is a simple example of how to use the canvas:
<html>
<head>
<script src="index.js"></script>
<body>
<canvas id="canvas" width="500" height="500" style="border: 1px solid black;" onmousemove="mouseClick(event)">></canvas>
</body>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
canvas = {}
var isMouseDown = false;
document.addEventListener('mousedown', function(event) {
if ( event.which ) isMouseDown = true;
}, true);
document.addEventListener('mouseup', function(event) {
if ( event.which ) isMouseDown = false;
}, true);
$(document).ready(function(){
canvas.cnv = document.getElementById("canvas");
canvas.Width = canvas.cnv.width;
canvas.Height = canvas.cnv.height;
canvas.ctx = canvas.cnv.getContext('2d');
});
function mouseClick(e) {
console.log(isMouseDown)
if (isMouseDown){
var x1 = event.offsetX;
var y1 = event.offsetY;
canvas.ctx.lineTo(x1, y1);
canvas.ctx.stroke();
}
}
</script>
</head>
</html>
I'm new in JS and trying to make simple interface with pure JS, where User can dynamically add elements and move them around.
I found solutions for create elements and drag'n'drop elements, that perfectly works separatly. But when I tried to unite them, drop function stop working...
What am I doing wrong?
Template:
<head>
<title>Int Demo</title>
<script src='js/script.js'></script>
<style type="text/css">
.wrapper {width: 300px; height: 200px; background: #A3A1A1;}
.textblock {cursor: pointer; background: red;}
</style>
</head>
<body>
<div class="button" id="button">Add Textbox</div>
<div class="wrapper" id="wrapper"></div>
</body>
</html>
My JS file:
document.addEventListener("DOMContentLoaded", function() { init(); }, false);
function init() {
button = document.getElementById('button');
wrapper = document.getElementById('wrapper');
button.addEventListener('click', btnClick, false);
wrapper.ondblclick = catchIt;
}
//add element
function btnClick() {
wrapper.innerHTML += '<p class="draggable textblock">Text Here!</p>';
sessionStorage.inputBoxes = wrapper;
console.log(sessionStorage);
}
// Activate Drag'n'Drop
document.onmousedown = function(e) {
var dragElement = e.target;
if (!dragElement.classList.contains('draggable')) return;
var coords, shiftX, shiftY;
startDrag(e.clientX, e.clientY);
document.onmousemove = function(e) {
moveAt(e.clientX, e.clientY);
};
dragElement.onmouseup = function() {
finishDrag();
};
function startDrag(clientX, clientY) {
shiftX = clientX - dragElement.getBoundingClientRect().left;
shiftY = clientY - dragElement.getBoundingClientRect().top;
dragElement.style.position = 'fixed';
document.body.appendChild(dragElement);
moveAt(clientX, clientY);
};
function finishDrag() {
dragElement.style.top = parseInt(dragElement.style.top) + pageYOffset + 'px';
dragElement.style.position = 'absolute';
document.onmousemove = null;
dragElement.onmouseup = null;
}
function moveAt(clientX, clientY) {
var newX = clientX - shiftX;
var newY = clientY - shiftY;
// bottom offset
var newBottom = newY + dragElement.offsetHeight;
if (newBottom > document.documentElement.clientHeight) {
var docBottom = document.documentElement.getBoundingClientRect().bottom;
var scrollY = Math.min(docBottom - newBottom, 10);
if (scrollY < 0) scrollY = 0;
window.scrollBy(0, scrollY);
newY = Math.min(newY, document.documentElement.clientHeight - dragElement.offsetHeight);
}
// top offset
if (newY < 0) {
var scrollY = Math.min(-newY, 10);
if (scrollY < 0) scrollY = 0;
window.scrollBy(0, -scrollY);
newY = Math.max(newY, 0);
}
if (newX < 0) newX = 0;
if (newX > document.documentElement.clientWidth - dragElement.offsetHeight) {
newX = document.documentElement.clientWidth - dragElement.offsetHeight;
}
dragElement.style.left = newX + 'px';
dragElement.style.top = newY + 'px';
}
return false;
}
I changed
dragElement.onmouseup = function() {
finishDrag();
};
into
document.onmouseup = function() {
finishDrag();
};
and it started working for me. This does mean that the end user will have to keep the mouse button pressed down to continue dragging and that the element will be placed immediately on mouse button up. But I'm assuming that this is the desired functionality, or do you want the drop to happen only on a second mouse click?
I want the coordinates calculated by "getPosition" to be available for use with other functions so that I don't have to write the rest of the code that uses x and y within getPosition.
I know I can use something like return {posX: x, posY: y}; to retrieve both values from the function but I don't know how to make them available outside of getPosition.
document.addEventListener("DOMContentLoaded", init, false);
function init()
{
var canvas = document.getElementById("canvas");
canvas.addEventListener("mousedown", getPosition, false);
}
function getPosition(event)
{
var x = new Number();
var y = new Number();
var canvas = document.getElementById("canvas");
if (event.x != undefined && event.y != undefined)
{
x = event.x;
y = event.y;
}
else // Firefox method to get the position
{
x = event.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = event.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
x -= canvas.offsetLeft;
y -= canvas.offsetTop;
}
Create a closure and put your variables x and y and the functions that use them in there:
(function(){
var _x = 0;
var _y = 0;
document.addEventListener("DOMContentLoaded", init, false);
function init()
{
var canvas = document.getElementById("canvas");
canvas.addEventListener("mousedown", getPosition, false);
}
function getPosition(event)
{
var x = new Number();
var y = new Number();
var canvas = document.getElementById("canvas");
if (event.x != undefined && event.y != undefined)
{
x = event.x;
y = event.y;
}
else // Firefox method to get the position
{
x = event.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = event.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
x -= canvas.offsetLeft;
y -= canvas.offsetTop;
//Save x and y for later
_x = x;
_y = y;
}
})();
I have this code for DnD an element. It works for an especific element. However I wanna make it work for all divs. I can't reference "this.id" to the move function. I don't what is missing to make it work.
window.addEventListener('load', init, false);
function init(){
//just one element
/* box = document.getElementById('div1');
box.addEventListener('mousedown', startMoving, false);
box.addEventListener('mouseup', stopMoving, false);*/
//all element?
box = document.getElementsByTagName('div');
for (i=0;i<box.length;i++) {
box[i].addEventListener('mousedown', startMoving, false);
box[i].addEventListener('mouseup', stopMoving, false);
}
}
function startMoving(evt){
evt = evt || window.event;
var posX = evt.clientX,
posY = evt.clientY,
a = document.getElementById(this.id);
divTop = parseInt(a.style.top),
divLeft = parseInt(a.style.left);
var diffX = posX - divLeft,
diffY = posY - divTop;
document.onmousemove = function(evt){
evt = evt || window.event;
var posX = evt.clientX,
posY = evt.clientY,
aX = posX - diffX,
aY = posY - diffY;
move(this.id,aX,aY);
}
}
function stopMoving(){
document.onmousemove = function(){}
}
function move(divid,newX,newY){
var a = document.getElementById(divid);
a.style.left = newX + 'px';
a.style.top = newY + 'px';
}
Is there a better way to make this?
I'm having a problem whit my code.
I draw some circles in a circular path and I expect when to click on them to return something other than 0 in firebug console but that's not happening;
I don't know what is wrong with my code and i hope someone will tell me.
Here's my code:
var canvas, ctx;
var circle_data = [];
function circles(x, y, radius) {
this.x = x;
this.y = y;
this.radius = radius;
circle_data.push(this);
}
circles.prototype = {
draw: function (context) {
context.beginPath();
context.arc(this.x, this.y, this.radius / 5, 0, 2 * Math.PI, false);
context.fillStyle = "red";
context.fill();
}
}
function draw() {
ctx.translate(250, 250);
for (var n = 0; n < 10; n++) {
var radi = (Math.PI / 180);
var x = Math.sin(radi * n * 36) * 70;
var y = Math.cos(radi * n * 36) * 70;
var radius = 50;
var thiscircle = new circles(x, y, radius);
thiscircle.draw(ctx);
}
}
function mouseDown(e) {
var img_data = ctx.getImageData(e.pageX, e.pageY, 1, 1);
console.log(img_data.data[3]);
}
function init() {
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
canvas.addEventListener('mousedown', mouseDown, false);
}
init();
It dosen't matter is i use data[3];
I tried whit console.log(img_data.data[0]+" "+img_data.data[1]+" "+img_data.data[2]);
Still getting 0 0 0
Your detecting the mouse position relative to the page and not the canvas, you need to get the position of the canvas on the page and subtract that from the X and Y of the mouse to find you position relative to the canvas. I use functions similar to the ones below when working with canvas.
getOffsetPosition = function(obj){
/*obj is the Canvas element*/
var offsetX = offsetY = 0;
if (obj.offsetParent) {
do {
offsetX += obj.offsetLeft;
offsetY += obj.offsetTop;
}while(obj = obj.offsetParent);
}
return [offsetX,offsetY];
}
getMouse = function(e,canvasElement){
OFFSET = getOffsetPosition(canvasElement);
mouse_x = (e.pageX || (e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft)) - OFFSET[0];
mouse_y = (e.pageY || (e.clientY + document.body.scrollTop + document.documentElement.scrollTop)) - OFFSET[1];
return [mouse_x,mouse_y];
}
The following code works.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<canvas id="canvas" width="500" height="500" style="background-color:#999999;"></canvas>
</body>
<script>
var canvas,ctx;
var circle_data = [];
function circles(x,y,radius)
{
this.x = x;
this.y = y;
this.radius = radius;
circle_data.push(this);
}
circles.prototype = {
draw: function(context){
context.beginPath();
context.arc(this.x, this.y, this.radius / 5, 0, 2* Math.PI, false);
context.fillStyle = "red";
context.fill();
}
}
getOffsetPosition = function(obj){
/*obj is the Canvas element*/
var offsetX = offsetY = 0;
if (obj.offsetParent) {
do {
offsetX += obj.offsetLeft;
offsetY += obj.offsetTop;
}while(obj = obj.offsetParent);
}
return [offsetX,offsetY];
}
getMouse = function(e,canvasElement){
OFFSET = getOffsetPosition(canvasElement);
mouse_x = (e.pageX || (e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft)) - OFFSET[0];
mouse_y = (e.pageY || (e.clientY + document.body.scrollTop + document.documentElement.scrollTop)) - OFFSET[1];
return [mouse_x,mouse_y];
}
function draw(){
ctx.translate(250, 250);
for (var n = 0; n < 10; n++) {
var radi = (Math.PI/180);
var x = Math.sin(radi*n*36)*70;
var y = Math.cos(radi*n*36)*70;
var radius = 50;
var thiscircle = new circles(x,y,radius);
thiscircle.draw(ctx);
}
}
function mouseDown(e)
{
var pos = getMouse(e,ctx.canvas);
var img_data = ctx.getImageData(pos[0],pos[1],1,1);
console.log(img_data.data[3]);
}
function init() {
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
draw();
canvas.addEventListener('mousedown', mouseDown, false);
}
init();
</script>
</html>