How to draw rectangles on SVG on click event? - javascript

I am using raphael js in my application. Here I need to draw a small rectangle on a point of clicking in raphael paper. I need to connect these rectangle using a line. Can anyone make DEMO of this. I am adding sample DEMO. Please update this.
My DEMO.:
HERE
var paper = Raphael("editor", 635,500),
canvas= document.getElementById('editor').style.backgroundColor='gray';
Now I need to draw samll rectangles on clicking raphael paper and joing them with a line.

This should do the trick; http://jsfiddle.net/9dsgcv1c/1/
var paper = Raphael("editor", 635,500),
canvas= document.getElementById('editor').style.backgroundColor='gray';
var offsetx = paper.canvas.offsetLeft;
var offsety = paper.canvas.offsetTop;
var prevRect = null;
var rWidth = 50;
paper.canvas.onmousedown = function(e) {
var posX = e.pageX-offsetx;
var posY = e.pageY-offsety;
var rectX = posX - (rWidth/2)
var rectY = posY - (rWidth/2)
var c = paper.rect(rectX, rectY, rWidth, rWidth).attr({fill:"#fff"});
if(prevRect) {
var p = "M"+prevRect.x +" " +prevRect.y +"L"+posX+" "+posY
var line = paper.path(p);
}
prevRect = {x: posX, y:posY};
}
-
<b>Click on CAMVAS to draw rectangle</b>
<div id="editor"></div>

Related

Canvas drawing wont show

I was making a web game just for a little practice, but my drawing will not show in the canvas element of the browser. I do not know why it will not show. By the way, I used variables as the value of the horizontal position so that I could easily change them later.
JavaScript
var canvas = getElementById('myCanvas');
var blt = canvas.getContext('2d');
var bS = 20;
var x = 220;
var y = 340;
var x1 = 227;
var x2 = 229;
var x3 = 240;
var x4 = 251;
var x5 = 253;
var x6 = 260;
function drawShip() {
blt.beginPath();
blt.moveTo(x,360);
blt.lineTo(x,340);
blt.lineTo(x1,337);
blt.lineTo(x2,337);
blt.lineTo(x2,340);
blt.lineTo(x3,330);
blt.lineTo(x4,340);
blt.lineTo(x4,337);
blt.lineTo(x5,337);
blt.lineTo(x6,340);
blt.lineTo(x6,360);
blt.lineTo(x,360);
blt.closePath();
};
drawShip();
You need to use the stroke() method to draw the path as a line.
Here you can find every canvas methods and some documentation and examples:
http://www.w3schools.com/tags/ref_canvas.asp
You forgot to stroke the path. Add this after blt.closePath()
blt.stroke();
In your code change the line
var canvas = getElementById('myCanvas');
by
var canvas = document.getElementById('myCanvas');
and add blt.stroke(); after blt.closePath();

Canvas Vertical Wave

I have this canvas have made in horizontal. But what I want to achive is a vertical wave. I tried to change the values from x to y but unfortunately that didn't work.
First thing I want to make it vertically. And after I achive that I want to make a square like this. But one step at a time.
On local I made the wave vertically but the mouse movement from this function didn't work.
function onMouseMove(event) {
var mouseX = event.clientX;
var mouseY = event.clientY;
var xPart;
if(Math.abs(_halfStageHeight - mouseY) < _colRadius) {
if(_allowHitBool){
_mouseYSpeed = mouseY - _oldMouseY;
xPart = Math.floor(mouseX/_particleDistNum);
_particleArray[xPart].yVel = _mouseYSpeed/2;
_allowHitBool = false;
setTimeout(function() {
_allowHitBool = true;
}, 100);
}
}
_oldMouseX = mouseX;
_oldMouseY = mouseY;
}
This is the horizontal wave. jsFiddle
Thank you
You could use transformations to rotate the canvas 90 degrees to vertical:
function init() {
var stage = document.getElementById('stage');
_stageWidth = stage.width = window.innerWidth;
_stageHeight = stage.height = window.innerHeight;
_halfStageHeight = _stageHeight/2;
_stageContext = stage.getContext('2d');
_stageContext.fillStyle = "#fff";
_particleDistNum = _stageWidth/(_totalParticles-1);
createParticles();
// rotate the canvas 90 degrees to vertical
_stageContext.translate(stage.width/2,stage.height/2);
_stageContext.rotate(Math.PI/2);
_stageContext.translate(-stage.width/2,-stage.height/2);
}

Raphael JS to draw concentric lines

I'm stuck using Raphael JS : I want to make a basic animation that draws concentric lines while loading some stuff.
So, I made this function :
function loadingButton(width, height) {
width = width ? width : 240;
height = height ? height : 240;
var loadingButton = Raphael("loading-button", width, height);
var center = 120,
xloc = center,
yloc = center,
R = 120,
imgW = 124,
imgH = 140;
var lines;
var percent = loadingButton.text(center, center, '0');
percent.attr({'font-size': 36, 'fill': '#fff'});
var count = 0;
var interval = setInterval(function(){
if( count <= 100){
var start_x = center+Math.round((center-30)*Math.cos(4*count*Math.PI/200));
var start_y = center+Math.round((center-30)*Math.sin(4*count*Math.PI/200));
var end_x = center+Math.round((center-10)*Math.cos(4*count*Math.PI/200));
var end_y = center+Math.round((center-10)*Math.sin(4*count*Math.PI/200));
lines = loadingButton.path("M"+start_x+" "+start_y+"L"+end_x+" "+end_y).attr({"stroke":"#FFF","stroke-width":"1"});
percent.attr({text: count});
count++;
}
else {
clearInterval(interval);
}
}, 50);
};
With live demo here : http://jsfiddle.net/rfuqjL65/
The thing is, as you can see on the fiddle, the animation is starting on the first quarter (90°), not on the top (0°).
And well, the problem is : I want the animation starts on the top.
Any ideas ?
I can't get your fiddle running, but:
You can add/substract Math.PI/2 to the angle argument (in radians) for Math.cos and Math.sin in your coordinate variables, that should do the trick!
http://jsfiddle.net/rfuqjL65/2/
I change your code. And this worked.
And also
var start_x = center+Math.round((center-30)*Math.sin(4*count*Math.PI/200));
var start_y = center-Math.round((center-30)*Math.cos(4*count*Math.PI/200));
var end_x = center+Math.round((center-10)*Math.sin(4*count*Math.PI/200));
var end_y = center-Math.round((center-10)*Math.cos(4*count*Math.PI/200));

Fixing the canvas offset in Raphael.js when DOM element centered

I'm creating circles in a Raphael.js Canvas with a clicking action. When the canvas is drawn at the origin of the website it works fine. But when I move it to the middle some type offseting happens and only when you click on the right side of the canvas the circles are drawn at the left side of the canvas. Even though I have my listener action to the canvas and not the div that the is append to, here is the code:
<body>
<div id="container"></div>
</body>
Here is the JS:
var canvas = Raphael("container", 500, 500);
var ourCanvas = $('svg').last();
ourCanvas.attr("id", "canvas");
var canvasHandler = $("#canvas");
//We create a div with a class to append our canvas
var containerHandler = $("#container");
var circleClass = $("circle.quincy");
var justDragged = false;
canvasHandler.mouseup(function (e) {
var mouseX = e.pageX;
var mouseY = e.pageY;
makeCircle(mouseX, mouseY);
});
function makeCircle(mouseX, mouseY) {
var radius;
var fill;
var thisCirclesID = String(new Date().getTime());
var circle = canvas.circle(mouseX, mouseY, 50).attr({
fill: "hsb(.8, 1, 1)",
stroke: "none",
opacity: .5,
});
}
Here is a JSFiddle
I wonder if the way that I'm using the event position is correct. Any suggestion is more than welcome.
Thanks
M
I figured it out after realizing that the offset of the new position of svg was causing the mouse event to not recognize its real position. I found this blog post that shows how to use the offsetParent method to calculate the new position of my canvas relative its parent . Here is the code:
$(document).ready(function () {
//We create our canvas and add an ID
var canvas = Raphael("container", 500, 500);
var ourCanvas = $('svg').last();
ourCanvas.attr("id", "canvas");
var canvasHandler = $("#canvas");
//We create a div with a class to append our canvas
var containerHandler = $("#container");
var circleClass = $("circle.quincy");
var justDragged = false;
canvasHandler.mouseup(function (e) {
var mouseX = e.pageX - findPos(this)[0];
var mouseY = e.pageY - findPos(this)[1];
makeCircle(mouseX, mouseY);
findPos(this);
console.log("This is the position of the mouse in X: " + e.pageX);
console.log("This is the position of the mouse in Y: " + e.pageY);
});
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj == obj.offsetParent);
console.log(curleft);
console.log(curtop);
// return [curleft, curtop];
}
return [curleft, curtop];
}
As you can see the findPos(obj) returns and array of the new position of X and Y. So I substract that to my mouseX and mouseY to get the real position on the svg when clicking.
Update
Doing more reading and asking around. I didn't realize what type of elements the web browser returns. Instead of using e.pageX and e.pageY. offsetX offers the position of the mouse in respect to the parent giving the real coordinates. So the code will look like this:
canvasHandler.mouseup(function (e) {
var mouseX = e.offsetX;
var mouseY = e.offsetY;
makeCircle(mouseX, mouseY);
findPos(this);
});
This makes it easier since the offset takes into consideration the real position of the mouse in respect to the element.

Place image on canvas at same x,y position as mouse onclick

I'm trying to make a web app that lets the user insert small images of characters on an html canvas. The plan is to have the user click a button on a virtual keyboard, and then click on the canvas to have the corresponding character appear wherever the user clicked. Right now I'm just trying to get one image to appear on the canvas when clicked, but so far it isn't doing anything. Here's the code I have now, which is embedded in the html file.
<script type="text/javascript">
var mathCanvas = document.getElementById("matharea");
var ctx = mathCanvas.getContext("2d");
var el = mathCanvas;
var xPos = 0;
var yPos = 0;
while(el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)){
xPos += el.offsetLeft - el.scrollLeft;
yPos += el.offsetTop - el.scrollTop;
el = el.parentNode;
}
var img = new Image();
img.src = "five.png";
mathCanvas.onclick = function(event){
var x = event.clientX - xPos;
var y = event.clientY - yPos;
ctx.drawImage(img,x,y);
};
</script>
I've tested the onclick event, and it returns coords, but the image won't appear. What's going wrong here?
This should work since the click event will be firing on the canvas itself:
var mathCanvas = document.getElementById("matharea");
var ctx = mathCanvas.getContext("2d");
var img = new Image();
img.src = "five.png";
mathCanvas.onclick = function(event){
var x = event.offsetX;
var y = event.offsetY;
ctx.drawImage(img,x,y);
};
To center the image on the point:
var mathCanvas = document.getElementById("matharea");
var ctx = mathCanvas.getContext("2d");
var img = new Image();
img.src = "five.png";
mathCanvas.onclick = function(event){
var x = Math.round(event.offsetX - img.width/2);
var y = Math.round(event.offsetY - img.height/2);
ctx.drawImage(img,x,y);
};

Categories

Resources