I am using transitionTo method of kineticJS to show animated rotation of a shape on click event of mouse. It works fine if we click the shape first time but then on subsequent clicks it does not rotate the shape. I want to show transition(rotation) of the shape by some angle every time I click on it. Please let me know the mistake I am making and how can I correct it??
This is the code I am using
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
canvas {
border: 1px solid #9C9898;
}
</style>
<script src="http://www.html5canvastutorials.com/libraries/kinetic-v3.9.6.js"></script>
<script>
window.onload = function() {
var stage = new Kinetic.Stage({
container: "container",
width: 578,
height: 200
});
var layer = new Kinetic.Layer({
x:stage.getWidth()/3 ,
y: stage.getHeight()/3
});
var rect = new Kinetic.Rect({
x: 239,
y: 75,
width: 100,
height: 50,
fill: "#00D2FF",
stroke: "black",
strokeWidth: 4,
centerOffset: [50, 100]
});
// add the shape to the layer
layer.add(rect);
// add the layer to the stage
stage.add(layer);
rect.on("click", function() {
rect.transitionTo({
rotation:2*Math.PI,
duration:1
});
stage.draw();
});
};
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
Try this:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
canvas {
border: 1px solid #9C9898;
}
</style>
<script src="http://www.html5canvastutorials.com/libraries/kinetic-v3.10.0.js"></script>
<script>
window.onload = function() {
var angle = 0;
var stage = new Kinetic.Stage({
container: "container",
width: 578,
height: 200
});
var layer = new Kinetic.Layer();
var rect = new Kinetic.Rect({
x: 239,
y: 75,
width: 100,
height: 50,
fill: "#00D2FF",
stroke: "black",
strokeWidth: 4
});
layer.add(rect);
stage.add(layer);
rect.on("click", function() {
angle += 2;
rect.transitionTo({
rotation: Math.PI * angle,
duration:1
});
});
};
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
The click was working just fine, however you were telling it to rotate to the same angel every time (why it only animates on the first click). I added a variable so that the angle increases 360 degrees every time you click on it.
Related
On the Konvajs chat stream someone recently asked for an example of drag-and-drop from a palette onto an HTML5 canvas fronted by the Konvajs library. There were no ready examples and I was curious about how to achieve it.
I answered the question in a codepen but decided to post here for (my own) future reference. See my answer below.
Here is my solution using jquery UI draggable & droppables. Konvajs requires jquery so the use of jquery UI is only a small step further. The palette is a set of small canvas elements with one shape drawn per draggable item. The palette can be housed on any html element and does not need to be attached to the main stage in any way.
// Set up the canvas to catch the dragged shapes
var s1 = new Konva.Stage({container: 'container1', width: 500, height: 200});
// add a layer to host the 'dropped' shapes.
var layer1 = new Konva.Layer({draggable: false});
s1.add(layer1);
// set up the palette of draggable shapes - 5 sample shapes.
var palletteEle = $('#pallette');
var d, ps, l, c;
for (var i = 0; i<5; i = i + 1){
// make a div to hold the shape
d = $('<div id="shape' + i + '" class="draggable">Shape</div>')
palletteEle.append(d)
// make a mini stage to hold the shape
ps = new Konva.Stage({container: 'shape' + i, width: 50, height: 50});
// make a layer to hold the shape
l = new Konva.Layer();
// add layer to palette
ps.add(l);
// make a shape - red circles for example
c = new Konva.Circle({x: 24, y: 24, radius: 22, fill: 'red', stroke: 'black'})
l.add(c);
ps.draw();
}
// make a crosshair to give some idea of the drop location
var cross = new Konva.Line({points: [10, 0, 10, 20, 10, 10, 0, 10, 20, 10],
stroke: 'gold',
strokeWidth: 1,
lineCap: 'round',
lineJoin: 'round'})
layer1.add(cross);
//s1.draw();
// make the main stage a drop target
$('#container1').addClass('droppable');
// function to move the cross hairs
function moveCross(x, y){
cross.x(x);
y = y - $('#container1').offset().top;
cross.y(y < 0 ? 0 : y);
s1.draw();
}
// draggable setup. Movecross used to move the crosshairs. More work needed but shows the way.
$( ".draggable" ).draggable({
zIndex: 100,
helper: "clone",
opacity: 0.35,
drag: function( event, ui ) {moveCross(ui.offset.left , ui.offset.top + $(this).offset().top)}
});
// set up the droppable
$( ".droppable" ).droppable({
drop: function( event, ui ) {
dropShape(ui.position.left, ui.position.top)
}
});
// Function to create a new shape when we drop something dragged from the palette
function dropShape() {
var c1 = new Konva.Circle({x: cross.x(), y: cross.y(), radius: 22, fill: 'red', stroke: 'black'});
layer1.add(c1);
cross.x(0); cross.y(0);
cross.moveToTop(); // move the cross to the top to stop going bahind previously dropped shapes.
s1.draw();
}
p
{
padding: 4px;
}
#container1
{
display: inline-block;
width: 500px;
height: 200px;
background-color: silver;
overflow: hidden;
}
#pallette
{
height: 52px; width: 500px;
border: 1px solid #666;
margin-bottom: 10px;
z-index: 10;
}
.draggable
{
width:50px;
height: 50px;
display: inline-block;
border: 1px solid #666;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdn.rawgit.com/konvajs/konva/1.6.5/konva.min.js"></script>
<p>Drag a red circle from the pallette and drop it on the grey canvas.
</p>
<div id='pallette'></div>
<div id='container1'></div>
I tried Vanquished Wombat's solution, it was a great example. But ultimately I wanted my palette to be separate from Konva. So I modified that original snippet to work with Html5 drag & drop, without any jQuery. See the snippet below. You can drag stars & circles from the palette into the Konva canvas. Currently you have to drop onto another shape, but you can modify it easily to drop anywhere on the canvas. I'm using text for the palette items and a custom image for the drag object just for fun. But you can just use an img instead of using the setDragImage code.
const CUSTOM_DATA_TYPE = 'text/x-node-type';
// Set up the canvas to catch the dragged shapes
var s1 = new Konva.Stage({
container: 'container1',
width: 500,
height: 200
});
// add a layer to host the 'dropped' shapes.
var layer1 = new Konva.Layer({
draggable: false
});
s1.add(layer1);
for (let t = 0; t < 10; t++) {
let rect = document.getElementById('container1').getBoundingClientRect();
let x = Math.floor(Math.random() * rect.width);
let y = Math.floor(Math.random() * rect.height);
let type = Math.floor(Math.random() * 100) % 2 == 0 ? 'circle' : 'star';
dropShape(x, y, type);
}
// Function to create a new shape when we drop something dragged from the palette
function dropShape(x, y, type) {
var shape;
if (type == 'circle') {
shape = new Konva.Circle({
x: x,
y: y,
radius: 22,
fill: 'blue',
stroke: 'black'
});
} else {
shape = new Konva.Star({
x: x,
y: y,
numPoints: 5,
innerRadius: 10,
outerRadius: 20,
fill: 'purple',
stroke: 'black'
});
}
layer1.add(shape);
s1.draw();
}
function cursorToCanvasPos(e) {
let clientRect = document.getElementById('container1').getBoundingClientRect();
let pointerPosition = {
x: e.clientX - clientRect.x,
y: e.clientY - clientRect.y,
};
return pointerPosition;
}
function getHoveredShape(e) {
let pointerPosition = cursorToCanvasPos(e);
return s1.getIntersection(pointerPosition);
}
function onDragStart(e, type) {
// Do this or other things can mess with your drag
e.stopPropagation();
e.dataTransfer.setData(CUSTOM_DATA_TYPE, type);
e.dataTransfer.effectAllowed = "all";
var dragIcon = document.createElement('img');
dragIcon.src = 'https://placehold.it/100x100';
dragIcon.width = 100;
e.dataTransfer.setDragImage(dragIcon, 150, 150);
}
function onDragOver(e) {
// Might break if you don't have this
e.stopPropagation();
// Breaks for sure if you don't have this
e.preventDefault();
let thing = getHoveredShape(e);
if (thing) {
e.dataTransfer.dropEffect = "move";
// Just fire off a custom even if you want to, this does nothing in this example.
thing.fire('htmlDragOver');
} else {
e.dataTransfer.dropEffect = "none";
}
}
function onDrop(e) {
e.stopPropagation();
let type = e.dataTransfer.getData(CUSTOM_DATA_TYPE);
let pos = cursorToCanvasPos(e);
dropShape(pos.x, pos.y, type);
}
p {
padding: 4px;
}
#container1 {
display: inline-block;
width: 500px;
height: 200px;
background-color: silver;
overflow: hidden;
}
#palette {
height: 52px;
width: 500px;
border: 1px solid #666;
margin-bottom: 10px;
z-index: 10;
}
#palette span {
width: 50px;
height: 25px;
display: inline-block;
border: 1px solid #666;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdn.rawgit.com/konvajs/konva/1.6.5/konva.min.js"></script>
<p>Drag circle/star from the palette onto an existing shape on the canvas below.
</p>
<div id='palette'>
<!-- Pre-load this image so it'll be used for our drag -->
<img src="https://placehold.it/100x100" style="display: none">
<span draggable="true" ondragstart="onDragStart(event, 'circle')">circle</span>
<span draggable="true" ondragstart="onDragStart(event, 'star')">star</span>
</div>
<div id='container1' ondragover="onDragOver(event)" ondrop="onDrop(event)"></div>
I want to allow a user to add shapes/resize them, with a shape panel like the one on this page:
https://logomakr.com/
I have read into this and the use HTML canvas seems inevitable. My issue is allowing the user to add more than 1 of each shape and allowing the user to resize each shape.
You can achieve that using a JavaScript canvas library, called FabricJS.
ᴅᴇᴍᴏ
var canvas = new fabric.Canvas('c');
function addRectangle() {
var rectangle = new fabric.Rect({
top: 65,
left: 65,
width: 50,
height: 50,
fill: '#03A9F4'
});
canvas.add(rectangle);
}
function addTriangle() {
var triangle = new fabric.Triangle({
top: 65,
left: 65,
width: 50,
height: 50,
fill: '#4CAF50'
});
canvas.add(triangle);
}
function addCircle() {
var circle = new fabric.Circle({
top: 65,
left: 65,
radius: 25,
fill: '#f44336'
});
canvas.add(circle);
}
body { margin: 10px 0 0 0 }
canvas { border: 1px solid #ccc }
button { margin-top: 9px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.14/fabric.min.js"></script>
<canvas id="c" width="180" height="180"></canvas>
<button onclick="addRectangle()">Add Rectangle</button>
<button onclick="addTriangle()">Add Triangle</button>
<button onclick="addCircle()">Add Circle</button>
To learn more about this library, refer to the official documentation.
I want to restrict the area that an image can be drawn on a canvas. I am using Fabric.js.
I tried the following link, but it didn't work for me. Set object drag limit in Fabric.js.
I want any part of the image that would be drawn outside the red rectangle (pictured below) to just not be drawn.
var canvas = new fabric.Canvas('canvas');
$("#canvascolor > input").click(function() {
canvas.setBackgroundImage(this.src, canvas.renderAll.bind(canvas), {
crossOrigin: 'anonymous'
});
});
// trigger the first one at startup
$("#canvascolor > input:first-of-type()")[0].click();
document.getElementById('file').addEventListener("change", function(e) {
var file = e.target.files[0];
var reader = new FileReader();
console.log("reader " + reader);
reader.onload = function(f) {
var data = f.target.result;
fabric.Image.fromURL(data, function(img) {
var oImg = img.set({
left: 140,
top: 100,
width: 250,
height: 200,
angle: 0
}).scale(0.9);
oImg.lockMovementX = true;
canvas.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({
format: 'png',
quality: 0.8
});
});
};
reader.readAsDataURL(file);
});
document.querySelector('#txt').onclick = function(e) {
e.preventDefault();
canvas.deactivateAll().renderAll();
document.querySelector('#preview').src = canvas.toDataURL();
};
canvas {
border: 1px solid black;
}
#canvascolor input {
height: 50px;
width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file">
<canvas id="canvas" width="520" height="520"></canvas>
<section id="canvascolor">
<input class="canvasborder" type="image" src="https://dl.dropboxusercontent.com/s/9leyl96qd3tytn8/tshirt-front.jpg">
<input class="canvasborder" type="image" src="https://dl.dropboxusercontent.com/s/tk0fs5v4muo6898/tshirt-back.jpg">
</section>
<button href='' id='txt' target="_blank">submit</button><br/>
<img id="preview" />
I extended your script to answer you.
For your use case it looks like you could use some clipping function and uniform centered scaling.
Anyway the main question about restricting area for drawing is this:
var canvas = new fabric.Canvas('canvas');
$("#canvascolor > input").click(function() {
canvas.setBackgroundImage(this.src, canvas.renderAll.bind(canvas), {
crossOrigin: 'anonymous'
});
});
// trigger the first one at startup
$("#canvascolor > input:first-of-type()")[0].click();
function clipTShirt(ctx) {
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
var x = 140, y = 100 ,w = 225, h = 300;
ctx.moveTo(x, y);
ctx.lineTo(x + w, y);
ctx.lineTo(x + w, y + h);
ctx.lineTo(x, y + h);
ctx.lineTo(x, y);
ctx.restore();
}
document.getElementById('file').addEventListener("change", function(e) {
var file = e.target.files[0];
var reader = new FileReader();
console.log("reader " + reader);
reader.onload = function(f) {
var data = f.target.result;
fabric.Image.fromURL(data, function(img) {
var oImg = img.set({
left: 140,
top: 100,
width: 250,
height: 200,
angle: 0,
lockUniScaling: true,
centeredScaling: true,
clipTo: clipTShirt
}).scale(0.9);
oImg.lockMovementX = true;
canvas.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({
format: 'png',
quality: 0.8
});
});
};
reader.readAsDataURL(file);
});
document.querySelector('#txt').onclick = function(e) {
e.preventDefault();
canvas.deactivateAll().renderAll();
document.querySelector('#preview').src = canvas.toDataURL();
};
canvas {
border: 1px solid black;
}
#canvascolor input {
height: 50px;
width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file">
<canvas id="canvas" width="520" height="520"></canvas>
<section id="canvascolor">
<input class="canvasborder" type="image" src="https://dl.dropboxusercontent.com/s/9leyl96qd3tytn8/tshirt-front.jpg">
<input class="canvasborder" type="image" src="https://dl.dropboxusercontent.com/s/tk0fs5v4muo6898/tshirt-back.jpg">
</section>
<button href='' id='txt' target="_blank">submit</button><br/>
<img id="preview" />
<html>
<head>
<style type="text/css">
canvas{
border:1px solid #ccc;
}
.canvas-container{
float: left;
left: 20px;
}
</style>
</head>
<body>
<canvas id='canvas' width='500' height='600' ></canvas>
<canvas id='C2' width='500' height='600'></canvas>
<script type="text/javascript" src="fabric.js"></script>
<script>
(function() {
var canvas = this.__canvas = new fabric.Canvas('canvas');
fabric.Object.prototype.transparentCorners = false;
var radius = 300;
fabric.Image.fromURL('./images/Chrysanthemum.jpg', function(img) {
img.scale(0.4).set({
left: 10,
top: 100,
angle: 0,
clipTo: function (ctx) {
ctx.rect(-250, -250, 400, 400);
}
});
canvas.add(img).setActiveObject(img);
console.log(canvas.getActiveObject());
});
})();
</script>
</body>
----------
</html>
//the code above;
Now the active object size is the same as the image which has not been cropped;
But if there is any way to make the cropped image to be selected.Means the smaller size which will be selected in a smaller size.
thx!
Clip is not meant for that effect:
If you desire some cropping better go with pattern trick if your cropping differs from what the attribute preserverveAspectRatio allows you.
(basically crop in center, crop left crop right, both for x and y axis).
As you see instead of image i create a rect with desired dimensions, then i use the img loaded to create a pattern that will fill the rect.
You can then use offsetX and offsetY on pattern to modify the part of image visible.
offsets are accessible trought:
rect.fill.offsetX
rect.fill.offsetY
(function() {
var canvas = this.__canvas = new fabric.Canvas('canvas');
fabric.Object.prototype.transparentCorners = false;
var radius = 300;
fabric.Image.fromURL('http://fabricjs.com/assets/pug.jpg', function(img) {
var rect = new fabric.Rect({width: 400, height: 400});
var pattern = new fabric.Pattern({source: img.getElement(), offsetX: -20, offsetY: -50});
rect.scale(0.4).set({
left: 10,
top: 100,
angle: 0,
fill: pattern,
});
canvas.add(rect).setActiveObject(rect);
});
})();
canvas{
border:1px solid #ccc;
}
.canvas-container{
float: left;
left: 20px;
}
<canvas id='canvas' width='500' height='600' ></canvas>
<canvas id='C2' width='500' height='600'></canvas>
<script type="text/javascript" src="http://fabricjs.com/lib/fabric.js"></script>
I am making an interactive world map in HTML5. I am using KineticJS to create the polygons of the countries, I currently have Australia and New Zealand. However I want it so if the mouse is over either Australia or New Zealand, they both will be highlighted. I don't know how to use Groups in KineticJS but this is how I tried (i used ellipses for the points because there are a lot of coordinates):
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#container {
background-image: url('world_map.png');
width: 1026px;
height: 540px;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.5.2.min.js"> </script>
<script defer="defer">
var stage = new Kinetic.Stage({
container: 'container',
width: 1026,
height: 540
});
var layer = new Kinetic.Layer();
var nznorth = new Kinetic.Polygon({
points: [...],
fill: '#ffffff',
stroke: 'black',
strokeWidth: 1
});
var nzsouth = new Kinetic.Polygon({
points: [...],
fill: '#ffffff',
stroke: 'black',
strokeWidth: 1
});
var ausmain = new Kinetic.Polygon({
points: [...],
fill: '#ffffff',
stroke: 'black',
strokeWidth: 1
});
var aus = new Kinetic.Group();
aus.add(ausmain);
aus.add(nznorth);
aus.add(nzsouth);
aus.on('mouseover', function() {
this.setFill('blue');
layer.draw();
});
aus.on('mouseout', function() {
this.setFill('#ffffff');
layer.draw();
});
layer.add(aus);
stage.add(layer);
</script>
</body>
</html>
How should I implement the group in KineticJS?
You just about have it !
When you handle your mouse events, set the fill on both Australia and New Zealand—not on the group.
group.on("mouseover",function(){
australia.setFill("blue");
newzealand.setFill("blue");
layer.draw();
console.log("over");
});
group.on("mouseout",function(){
australia.setFill("skyblue");
newzealand.setFill("skyblue");
layer.draw();
console.log("out");
});
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/LXvkg/
<!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.5.1.min.js"></script>
<style>
#container{
border:solid 1px #ccc;
margin-top: 10px;
}
</style>
<script>
$(function(){
var stage = new Kinetic.Stage({
container: 'container',
width: 400,
height: 400
});
var layer = new Kinetic.Layer();
stage.add(layer);
stage.draw();
var group=new Kinetic.Group();
layer.add(group);
var australia = new Kinetic.Rect({
x: 20,
y: 20,
width: 150,
height: 100,
fill: "skyblue",
stroke: "lightgray",
strokeWidth: 3
});
group.add(australia);
var newzealand = new Kinetic.Rect({
x: 250,
y: 110,
width: 20,
height: 50,
fill: "skyblue",
stroke: "lightgray",
strokeWidth: 3
});
group.add(newzealand);
layer.draw();
group.on("mouseover",function(){
australia.setFill("blue");
newzealand.setFill("blue");
layer.draw();
console.log("over");
});
group.on("mouseout",function(){
australia.setFill("skyblue");
newzealand.setFill("skyblue");
layer.draw();
console.log("out");
});
}); // end $(function(){});
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
This tutorial should help you to implement Kinetic groups.
http://www.html5canvastutorials.com/kineticjs/html5-canvas-complex-shapes-using-groups-with-kineticjs/