Reduce radius of circle on mousemove kineticjs - javascript

I'm trying to create a html5 canvas painting application using kinetic.js where users can select various shapes and draw them on canvas .
When a user selects circle and tries to draw it , the radius of circle should depend on the distance the mouse has covered on the canvas , now the problem is when the radius of circle increase it works fine but when I decrease it the circle remain of same size .
It would be great if someone can point me to the right direction .
Here is the link to fiddle . http://jsfiddle.net/45fEn/
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div id="container"></div>
<script src="kinetic.js"></script>
<script src="js/jquery.js"></script>
<script defer="defer">
$(document).ready(function() {
var stage = new Kinetic.Stage({
container:'container',
width:300,
height:400
});
var layer = new Kinetic.Layer();
function drawCircle() {
var circle = new Kinetic.Circle({
x:initialX, y:initialY , radius:tangant , fill:'green'
});
layer.add(circle) ;
stage.add(layer);
}
stage.add(layer);
var painting =false , clicking = false ;
var initialX , initialY , finalX , finalY , tangant , newTangant ,storeTime;
$("canvas").mousedown(function(ev) {
initialX = ev.clientX;
initialY = ev.clientY;
painting = true;
clicking = true;
});
$("canvas").mousemove(function(ev) {
finalX = ev.clientX ;
finalY = ev.clientY ;
var diffX = initialX - finalX ;
var diffY = initialY - finalY ;
tangant = Math.sqrt ( Math.pow(diffX,2) + Math.pow(diffY,2) ) ;
console.log(tangant);
storeTime = setTimeout(function() { newTangant = tangant },200) ;
if(newTangant < tangant) { console.log("new tan:"+newTangant);
circle.remove();
drawCircle();
}
if(clicking == true) {
drawCircle();
}
});
$("canvas").mouseup(function(ev) {
painting = false;
clicking = false;
});
});
</script>
</body>
</html>

You’re close!
BTW, you can also use stage.getContent to hook into stage mouse events.
stage.getContent()).on('mousedown', function (event) { …do mousedown stuff… }
Instead of removing and recreating the circle...
...just use circle.setRadius(newRadius) to resize the existing circle.
$(stage.getContent()).on('mousemove', function (event) {
if(!isDragging){return;}
var pos=stage.getMousePosition();
var mouseX=parseInt(pos.x);
var mouseY=parseInt(pos.y);
var dx=mouseX-initialX;
var dy=mouseY-initialY;
var r=Math.sqrt(dx*dx+dy*dy);
// this will resize the circle that is currently being created/resized
draggedCircle.setRadius(r);
layer.draw();
});
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/KLcRc/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Prototype</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.0.min.js"></script>
<style>
#container{
border:solid 1px #ccc;
margin-top: 10px;
width:400px;
height:400px;
}
</style>
<script>
$(function(){
var stage = new Kinetic.Stage({
container: 'container',
width: 400,
height: 400
});
var layer = new Kinetic.Layer();
stage.add(layer);
var draggedCircle,initialX,initialY;
var radius=25;
var isDragging=false;
function newCircle(mouseX,mouseY){
initialX=mouseX;
initialY=mouseY;
var circle = new Kinetic.Circle({
x:initialX,
y:initialY ,
radius:1,
fill:'green'
});
layer.add(circle) ;
layer.draw();
return(circle);
}
$(stage.getContent()).on('mousedown', function (event) {
var pos=stage.getMousePosition();
var mouseX=parseInt(pos.x);
var mouseY=parseInt(pos.y);
draggedCircle=newCircle(mouseX,mouseY);
isDragging=true;
});
$(stage.getContent()).on('mousemove', function (event) {
if(!isDragging){return;}
var pos=stage.getMousePosition();
var mouseX=parseInt(pos.x);
var mouseY=parseInt(pos.y);
var dx=mouseX-initialX;
var dy=mouseY-initialY;
var r=Math.sqrt(dx*dx+dy*dy);
draggedCircle.setRadius(r);
layer.draw();
});
$(stage.getContent()).on('mouseup', function (event) {
isDragging=false;
});
}); // end $(function(){});
</script>
</head>
<body>
<p>Drag to create a resizable circle</p>
<div id="container"></div>
</body>
</html>

Related

HTML5 Canvas how to make image can resizable by Kinetic.js?

I have add image function :
$("ul#img a").click(function(){
addProduct( $('img', this) );
});
function addProduct( imgObj ){
var layer = new Kinetic.Layer();
var imageObj = new Image(); //createimage
imageObj.onload = function() {
var image = new Kinetic.Image({
x: stage.getWidth() / 2 - 53,
y: stage.getHeight() / 2 - 59,
image: imageObj,
draggable: true,
name: "image"
});
// add the shape to the layer
layer.add(image);
// add the layer to the stage
stage.add(layer);
=========== End function add Image to canvas ============
image.on("mouseover", function(){
var imagelayer = this.getLayer();
document.body.style.cursor = "move";
this.setStrokeWidth(2);
this.setStroke("white"); //It's border of image when hover
layer.draw();
writeMessage(messageLayer, "Delete it");}); //DeleteItem
image.on("mouseout", function(){
var imagelayer = this.getLayer();
document.body.style.cursor = "default";
this.setStrokeWidth(0);
this.setStroke("transparent");
layer.draw();
writeMessage(messageLayer, "");});
image.on("dblclick dbltap", function(){
layer.remove(image);
layer.clear();
layer.draw();});};
imageObj.src = imgObj.attr('src'); }
=========== End Event of Image ============
This code can add image to canvas ,can dragable but cant resizable
How to make this image can resizable?
Please explain to me please
Thank you so much.
Kinetic elements do not have a built-in way to let the user resize.
Here's code to let the user drag the right edge of the image to resize the image:
Listen for mousedown, mouseup and mousemove
If mousedown occurs on the right edge of the image, save that mouse x,y,
On each mousemove, scale the image by the aspect ratio created by the distance the mouse has moved.
Example code to get you started:
var stage = new Kinetic.Stage({
container: 'container',
width: 350,
height: 350
});
var layer = new Kinetic.Layer();
stage.add(layer);
var kImage;
var startRight=-1;
var startWidth=0;
var startHeight=0;
var img=new Image();
img.crossOrigin="anonymous";
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/facesSmall.png";
function start(){
kImage = new Kinetic.Image({
image:img,
x:10,
y:10,
width:img.width,
height:img.height,
});
layer.add(kImage);
layer.draw();
}
$(stage.getContent()).on('mousedown', function (event) {
var pos=stage.getPointerPosition();
var mouseX=parseInt(pos.x);
var mouseY=parseInt(pos.y);
var ipos=kImage.position();
var isize=kImage.getSize();
var right=ipos.x+isize.width;
if(mouseX>right-10 && mouseX<right+10){
startRight=mouseX;
startWidth=isize.width;
startHeight=isize.height;
}
});
$(stage.getContent()).on('mouseup', function (event) {
startRight=-1;
});
$(stage.getContent()).on('mousemove', function (event) {
if(startRight>=0){
var pos=stage.getPointerPosition();
var mouseX=parseInt(pos.x);
var mouseY=parseInt(pos.y);
var dx=mouseX-startRight;
var scaleFactor=(mouseX-(startRight-startWidth))/startWidth;
kImage.width(startWidth*scaleFactor);
kImage.height(startHeight*scaleFactor);
layer.draw();
}
});
body{padding:20px;}
#container{
border:solid 1px #ccc;
margin-top: 10px;
width:350px;
height:350px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/kineticjs/5.2.0/kinetic.js"></script>
<h4>Drag the right border of the image to resize<br>it while maintaining aspect ratio.</h4>
<div id="container"></div>

Selecting an Image in KineticJS

I have multiple images in Kineticjs stage. I have to get the properties of the image (x, y, height, width) on clicking on the image.
Here's an example of how to have a Kinetic.Image report it's XY when clicked.
preload all your images first
attach the click event to each new Kinetic.Image
Example code and a Demo: http://jsfiddle.net/m1erickson/58a89/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Prototype</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.0.1.min.js"></script>
<style>
body{padding:20px;}
#container{
border:solid 1px #ccc;
margin-top: 10px;
width:350px;
height:350px;
}
</style>
<script>
$(function(){
var stage = new Kinetic.Stage({
container: 'container',
width: 350,
height: 350
});
var layer = new Kinetic.Layer();
stage.add(layer);
// first fully load all images into imgs[]
// then call start() when all are loaded
var imageURLs=[]; // put the paths to your images here
var imagesOK=0;
var imgs=[];
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-1.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-2.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-3.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-4.jpg");
loadAllImages(start);
function loadAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}
}
function start(){
// the imgs[] array holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
for(var i=0;i<imgs.length;i++){
addImage(imgs[i],i*60,10,50,50);
}
}
function addImage(img,x,y,w,h){
var image=new Kinetic.Image({
x:x,
y:y,
width:w,
height:h,
image:img,
draggable:true
});
image.on("click",function(){
var pos=this.position();
alert(parseInt(pos.x)+","+parseInt(pos.y));
});
layer.add(image);
layer.draw();
}
}); // end $(function(){});
</script>
</head>
<body>
<h4>Drag to new position. Click to get XY.</h4>
<div id="container"></div>
</body>
</html>
When you load the images, bind a click event :
imageObj.onload = function(){
var currentImg = new Kinetic.Image({
// define x,y,W and H
});
currentImg.on("click", function(e) {
//x position for example
console.log(currentImg.getPosition().x);
});
}

kinetic layer is not working on touch event in javascript

I am trying to draw a line when user touch the Screen of Android/Iphone Device. I am using kinetic-v4.7.2.min.js. It works perfect on DeskTop. But not working on Devic. So i just change the mouse click events to Touch events. But, still its not working on touch of Device. It trigger the function perfect but it does not draw any line & does not add the line to the layer. Any idea?
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript"
src="http://code.jquery.com/jquery.min.js"></script>
<script
src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.2.min.js"></script>
<style>
#container {
border: solid 1px #ccc;
margin-top: 10px;
}
</style>
<script>
//create a stage and a layer
$(function() {
window.addEventListener('load', function(){ // on page load
document.body.addEventListener('touchstart', function(e){
// alert(e.changedTouches[0].pageX) // alert pageX coordinate of touch point
}, false)
}, false)
var isdrawing = false;
var stage;
var layer;
var background;
function InitLayer() {
stage = new Kinetic.Stage({
container : 'container',
width : 350,
height : 350
});
layer = new Kinetic.Layer();
stage.add(layer);
}
// an empty stage does not emit mouse-events
// so fill the stage with a background rectangle
// that can emit mouse-events
function drawRect() {
background = new Kinetic.Rect({
x : 0,
y : 0,
width : stage.getWidth(),
height : stage.getHeight(),
fill : 'white',
stroke : 'black',
strokeWidth : 1,
})
layer.add(background);
layer.draw();
// a flag we use to see if we're dragging the mouse
isMouseDown = false;
// a reference to the line we are currently drawing
newline;
// a reference to the array of points making newline
points = [];
}
//a flag we use to see if we're dragging the mouse
var isMouseDown;
// a reference to the line we are currently drawing
var newline;
// a reference to the array of points making newline
var points = [];
InitLayer();
drawRect();
// on the background
// listen for mousedown, mouseup and mousemove events
background.on('touchstart', function(e) {
//alert(e.changedTouches[0].pageX)
//onMousedown();
isdrawing = true;
isMouseDown = true;
points = [];
points.push(stage.getMousePosition());
var line = new Kinetic.Line({
points : points,
stroke : "green",
strokeWidth : 5,
lineCap : 'round',
lineJoin : 'round'
});
layer.add(line);
newline = line;
});
background.on('touchend', function() {
//onMouseup();
isMouseDown = false;
});
background.on('touchmove', function() {
//onMousemove();
if (!isMouseDown) {
return;
}
;
points.push(stage.getMousePosition());
newline.setPoints(points);
// use layer.drawScene
// this is faster since the "hit" canvas is not refreshed
layer.drawScene();
});
$('#clear').on('click', function() {
layer.removeChildren().add(background).draw();
isdrawing = false;
});
$('#save').on(
'click',
function() {
var img = $('.kineticjs-content').find('canvas').get(0)
.toDataURL("myimage/png");
if (isdrawing) {
$('body').prepend('<img src="' + img + '">');
}
});
});
</script>
</head>
<body>
<h3>Drag to sketch</h3>
<button id="save">SAVE as PNG</button>
<button id="clear">CLEAR</button>
<div id="container"></div>
</body>
</html>
Any Help would be appreciated!! Thanks.
You use stage.getMousePosition() to get the position in your touchmove event:
background.on('touchmove', function() {
//onMousemove();
if (!isMouseDown) {
return;
}
;
points.push(stage.getMousePosition());
newline.setPoints(points);
// use layer.drawScene
// this is faster since the "hit" canvas is not refreshed
layer.drawScene();
});
But you should use stage.getPointerPosition() instead.

KineticJS - Drawing Lines with Mouse

I'm using KinectJS to draw lines based on mouse movement. When a user holds down the mouse button, I want it to be the 'start' point of the line, and when the user release, it will be the 'end' of the line, but as they are holding the mouse down I want to be able to dynamically redraw the line as my mouse moves. Is this possible?
Yes, its possible.
Basically, you has to redraw your layer during onMouseMove event. You'll need a flag to control when the line is moving or not.
When the script initialize, this flag should be false.
At onMouseDown, the line start should receive the current mouse coordinates and set the flag to true.
At onMouseMouve, if the flag is true, you should update the line end to receive the current mouse coordinates.
At onMouseUp, the flag should be set to false.
See the example below:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
canvas {
border: 1px solid #9C9898;
}
</style>
<script src="http://www.html5canvastutorials.com/libraries/kinetic-v4.0.1.js"></script>
<script>
window.onload = function() {
layer = new Kinetic.Layer();
stage = new Kinetic.Stage({
container: "container",
width: 320,
height: 320
});
background = new Kinetic.Rect({
x: 0,
y: 0,
width: stage.getWidth(),
height: stage.getHeight(),
fill: "white"
});
line = new Kinetic.Line({
points: [0, 0, 50, 50],
stroke: "red"
});
layer.add(background);
layer.add(line);
stage.add(layer);
moving = false;
stage.on("mousedown", function(){
if (moving){
moving = false;layer.draw();
} else {
var mousePos = stage.getMousePosition();
//start point and end point are the same
line.getPoints()[0].x = mousePos.x;
line.getPoints()[0].y = mousePos.y;
line.getPoints()[1].x = mousePos.x;
line.getPoints()[1].y = mousePos.y;
moving = true;
layer.drawScene();
}
});
stage.on("mousemove", function(){
if (moving) {
var mousePos = stage.getMousePosition();
var x = mousePos.x;
var y = mousePos.y;
line.getPoints()[1].x = mousePos.x;
line.getPoints()[1].y = mousePos.y;
moving = true;
layer.drawScene();
}
});
stage.on("mouseup", function(){
moving = false;
});
};
</script>
</head>
<body>
<div id="container" ></div>
</body>
</html>

Adding events to Raphael elements

Hey, I'm trying to add a mousemove and click event to an SVG Raphael Rectangle:
Fiddle: http://jsfiddle.net/neuroflux/nXKbW/1/
Code:
tile = ctx.rect(x*10,y*(i*10),10,10).attr({
fill:'#000000',
stroke: '#ffffff'
});
tile.mouseover(function(e) {
pX = e.pageX;
pY = e.pageY;
});
tile.click(function() {
console.log('x: '+pX+'| y:'+pY);
});
Obviously, for some reason this doesn't function - I get no output onClick :'(
Ok I've got the click function to work. Finally ^_^.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="https://github.com/DmitryBaranovskiy/raphael/raw/master/raphael-min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
/* GLOBAL VARIABLES */
var drawFrames;
var canvas;
var ctx;
var universe = new Array();
var tile;
var pX,pY = 0;
universe = (
[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],
[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],
[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],
[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],
[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],
[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],
[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],
[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],
[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],
[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]]
);
/* WINDOW LOAD */
window.onload = function() {
init();
}
/* INITIALISATION */
function init() {
ctx = Raphael(10, 50, 320, 200);
drawFrames = setInterval(drawFrame, 40);
}
/* FRAME RENDER LOOP */
function drawFrame() {
//ctx.clear();
for (var x = 0; x < universe.length; x++) {
for (var y = 0; y < universe[x].length; y++) {
for (var i= 0; i < 11; i++) {
tile = ctx.rect(x*10,y*(i*10),10,10).attr({
fill:'#000000',
stroke: '#ffffff'
}).click(function(e) {
console.log('x: '+e.pageX+'| y:'+e.pageY);
})
}
}
}
}
</script>
</head>
<body>
<canvas id="main" width="800" height="600">
<h1>No Support I'm Afraid...</h1>
</canvas>
</body>
</html>
first give your raphael object an id then bind the click event to it.
tile = ctx.rect(x*10,y*(i*10),10,10).attr({
fill:'#000000',
stroke: '#ffffff'
});
tile.node.id='tile_id';
$('#tile_id').bind('click',function(){alert('clicked');});

Categories

Resources