Javascript: No response after preload of images - javascript

Okay, I now tried to load two Kinetic images, but it still doesn't work. I also tried to put it on another layer and on another stage. Nothing helped. But with one image everything is fine.
var stage = new Kinetic.Stage({
container: 'container',
width: 1600,
height: 1000
});
var layer = new Kinetic.Layer();
var imageObj = new Image();
imageObj.onload = function() {
var yoda = new Kinetic.Image({
x: 200,
y: 50,
image: imageObj,
width: 106,
height: 118
});
var imageObj2 = new Image();
imageObj2.onload = function() {
var vader = new Kinetic.Image({
x: 400,
y: 200,
image: imageObj2,
width: 206,
height: 218
});
// add the shape to the layer
layer.add(yoda);
layer.add(vader);
// add the layer to the stage
stage.add(layer);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/yoda.jpg';
imageObj2.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
OLD:
This is a sample code from http://www.html5canvastutorials.com/. I want to load two (or more) images and animate them both by clicking one button. Everything works fine with one picture, but this code confuses me. After the loadImages function is called there is no more reaction, even an alert isn't displayed. Where and how can I place my anim function?(I will implement the other animation later) Thanks for your ideas!
CSS
body {
margin: 0px;
padding: 0px;
}
#buttons {
position: absolute;
top: 50px;
left: 100px;
}
#buttons > input {
padding: 10px;
display: block;
margin-top: 5px;
}
HTML
<div id="container"></div>
<div id="buttons">
<input type="button" id="start" value="Start">
</div>
<canvas id="myCanvas" width="578" height="200"></canvas>
JS
document.getElementById('start').addEventListener('click', function() {
anim.start(); //button should start animation
}, false);
function loadImages(sources, callback) {
var images = {};
var loadedImages = 0;
var numImages = 0;
// get num of sources
for(var src in sources) {
numImages++;
}
for(var src in sources) {
images[src] = new Image();
images[src].onload = function() {
if(++loadedImages >= numImages) {
callback(images);
}
};
images[src].src = sources[src];
}
}
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var sources = {
darthVader: 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg',
yoda: 'http://www.html5canvastutorials.com/demos/assets/yoda.jpg'
};
loadImages(sources, function(images) {
context.drawImage(images.darthVader, 100, 30, 200, 137);
context.drawImage(images.yoda, 150, 55, 93, 104);
});
var angularSpeed = 360 / 4; //from this line on it's like the js-code doesn't exist
var anim = new Kinetic.Animation(function(frame) { exist
var angleDiff = frame.timeDiff * angularSpeed / 1000;
images.yoda.rotate(angleDiff); //sources. instead images.?
}, layer);

You are mixing html5 canvas code with KineticJS library code.
You must create Kinetic.Image objects from each of your image objects.
Only then you can use Kinetic.Animation to animate them into rotation.

Related

KonvaJS - Toggle anchors when mouseon/mouseoff of image

In my KonvaJS project, I'm adding images aka "stickers" onto an uploaded image, and with KonvaJS, I'm adding "Anchors" to rotate and resize the images.
When the mouse is off the main image, (or maybe when you click on the sticker, it toggles edit mode?), I'd like to remove the anchors and lines.
How is this possible?
function centreRectShape(shape) {
shape.x((stage.getWidth() - shape.getWidth()) / 2);
shape.y((stage.getHeight() - shape.getHeight()) / 2);
}
var stage = new Konva.Stage({
container: 'canvas-container',
width: 650,
height: 300
});
var layer = new Konva.Layer();
stage.add(layer);
var bgRect = new Konva.Rect({
width: stage.getWidth(),
height: stage.getHeight(),
fill: 'gold',
opacity: 0.1
});
layer.add(bgRect);
var uploadedImage = new Konva.Image({
draggable: false
});
layer.add(uploadedImage);
imgObj = new Image();
imgObj.onload = function() {
uploadedImage.image(imgObj);
var padding = 20;
var w = imgObj.width;
var h = imgObj.height;
var targetW = stage.getWidth() - (2 * padding);
var targetH = stage.getHeight() - (2 * padding);
var widthFit = targetW / w;
var heightFit = targetH / h;
var scale = (widthFit > heightFit) ? heightFit : widthFit;
w = parseInt(w * scale, 10);
h = parseInt(h * scale, 10);
uploadedImage.size({
width: w,
height: h
});
centreRectShape(uploadedImage);
layer.draw();
}
imgObj.src = 'https://images.pexels.com/photos/787961/pexels-photo-787961.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260';
$('.sticker').on('click', function() {
addSticker($(this).attr('src'));
});
function addSticker(imgUrl) {
stickerObj = new Konva.Image({
x: 240,
y: 20,
width: 93,
height: 104,
draggable: true
});
layer.add(stickerObj);
var stickerImage = new Image();
stickerImage.onload = function() {
stickerObj.image(stickerImage);
layer.draw();
};
stickerImage.src = imgUrl;
var imgRotator = new Konva.Transformer({
node: stickerObj,
keepRatio: true,
enabledAnchors: ['top-left', 'top-right', 'bottom-left', 'bottom-right']
});
layer.add(imgRotator);
}
html,
* {
margin: 0;
padding: 0;
}
body {
background: #eee;
}
#image-editor {
background: #fff;
border-radius: 3px;
border: 1px solid #d8d8d8;
width: 650px;
margin: 0 auto;
margin-top: 20px;
box-shadow: 0 3px 5px rgba(0, 0, 0, .2);
}
.stickers {
padding: 10px 5px;
background: #eee;
}
.stickers>img {
margin-right: 10px;
}
<script src="https://unpkg.com/konva#2.4.1/konva.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="image-editor">
<div id="canvas-container"></div>
<div class="stickers">
<div>
click sticer below and then rotate
</div>
<img class="sticker" src="https://craftblock.me/koa/fb-upload-clone/stickers/sticker%20(1).png" alt="Sticker" width="62px">
</div>
</div>
The most simple way is to add to the addSticker() function event handlers for both mouseover and mouseout. You can attach them, e. g., to the stage object.
stage.on('mouseover', function() {
imgRotator.attachTo(stickerObj);
layer.draw();
});
stage.on('mouseout', function() {
imgRotator.detach();
layer.draw();
});
They do two things:
attach / detach the Transformer object to / from the selected node.
refresh the layer.
From here on you can improve it. You could make the addSticker() function to return an object with the attachTo and detach methods to be able to call them from somewhere else. Something like:
function addSticker(imgUrl) {
...
return {
showTransformer: function() {
imgRotator.attachTo(stickerObj);
layer.draw();
},
hideTransformer: function() {
imgRotator.detach();
layer.draw();
}
};
}
Also, if you mean to have more than one sticker, you should implement some logic to track to which sticker should the events apply.
Edit:
You have made two comments to this answer:
"I think it's best if the mouseout is for that specific sticker."
The anchors to resize and rotate the image are actually outside the image. If you hide them after the mouseout event... well, your users will never reach them ;)
You have two options to avoid it:
Create a custom hit region which includes the anchors.
Replace the event with a click to toggle the transformer object.
I use the second approach in the updated snippet.
"What if there's multiple added stickers?"
You should use a closure to keep the references to the different objects in the scope of that functions.
Combining the click to toggle and the closure we have:
stickerObj.on('click', (function(transformer, sticker) {
return function() {
transformer.getNode() ? transformer.detach() : transformer.attachTo(sticker);
layer.draw();
};
})(imgRotator, stickerObj));
Extra tips:
Even after detaching the transformer, the user will be still able to move the image around. That's because draggable is a property of the image (inherited from node), not of the transformer.
So maybe you also want to toggle node.draggable(boolean);.
If for some reasons you don't want to detach/attach the transformer, you can achieve a similar effect toggling borderEnabled(), resizeEnabled() and rotateEnabled().
function centreRectShape(shape) {
shape.x((stage.getWidth() - shape.getWidth()) / 2);
shape.y((stage.getHeight() - shape.getHeight()) / 2);
}
var stage = new Konva.Stage({
container: 'canvas-container',
width: 650,
height: 300
});
var layer = new Konva.Layer();
stage.add(layer);
var bgRect = new Konva.Rect({
width: stage.getWidth(),
height: stage.getHeight(),
fill: 'gold',
opacity: 0.1
});
layer.add(bgRect);
var uploadedImage = new Konva.Image({
draggable: false
});
layer.add(uploadedImage);
imgObj = new Image();
imgObj.onload = function() {
uploadedImage.image(imgObj);
var padding = 20;
var w = imgObj.width;
var h = imgObj.height;
var targetW = stage.getWidth() - (2 * padding);
var targetH = stage.getHeight() - (2 * padding);
var widthFit = targetW / w;
var heightFit = targetH / h;
var scale = (widthFit > heightFit) ? heightFit : widthFit;
w = parseInt(w * scale, 10);
h = parseInt(h * scale, 10);
uploadedImage.size({
width: w,
height: h
});
centreRectShape(uploadedImage);
layer.draw();
}
imgObj.src = 'https://images.pexels.com/photos/787961/pexels-photo-787961.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260';
$('.sticker').on('click', function() {
addSticker($(this).attr('src'));
});
function addSticker(imgUrl) {
stickerObj = new Konva.Image({
x: 240,
y: 20,
width: 93,
height: 104,
draggable: true
});
layer.add(stickerObj);
var stickerImage = new Image();
stickerImage.onload = function() {
stickerObj.image(stickerImage);
layer.draw();
};
stickerImage.src = imgUrl;
var imgRotator = new Konva.Transformer({
node: stickerObj,
keepRatio: true,
enabledAnchors: ['top-left', 'top-right', 'bottom-left', 'bottom-right']
});
layer.add(imgRotator);
stickerObj.on('click', (function(transformer, sticker) {
return function() {
transformer.getNode() ? transformer.detach() : transformer.attachTo(sticker);
layer.draw();
};
})(imgRotator, stickerObj));
}
html,
* {
margin: 0;
padding: 0;
}
body {
background: #eee;
}
#image-editor {
background: #fff;
border-radius: 3px;
border: 1px solid #d8d8d8;
width: 650px;
margin: 0 auto;
margin-top: 20px;
box-shadow: 0 3px 5px rgba(0, 0, 0, .2);
}
.stickers { pitón reticulada
padding: 10px 5px;
background: #eee;
}
.stickers>img {
margin-right: 10px;
}
<script src="https://unpkg.com/konva#2.4.1/konva.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="image-editor">
<div id="canvas-container"></div>
<div class="stickers">
<div>
click sticer below and then rotate
</div>
<img class="sticker" src="https://craftblock.me/koa/fb-upload-clone/stickers/sticker%20(1).png" alt="Sticker" width="62px">
</div>
</div>

Konva how to transform image

I follow the Documentation that Konva have.
https://konvajs.github.io/docs/select_and_transform/Basic_demo.html
and
https://konvajs.github.io/docs/sandbox/Image_Resize.html
But the problem is they only have transform demo for rectangle shape. My plan is to have it on image. But so far I cant get it right. Here's my example code.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/konvajs/konva/master/konva.min.js"></script>
<meta charset="utf-8">
<title>Konva Image Resize Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #F0F0F0;
}
</style>
</head>
<body class="col-md-12">
<div id="container" class="col-md-10">
</div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;
function testFunction() {
addCanvas();
}
function update(activeAnchor) {
var group = activeAnchor.getParent();
var topLeft = group.get('.topLeft')[0];
var topRight = group.get('.topRight')[0];
var bottomRight = group.get('.bottomRight')[0];
var bottomLeft = group.get('.bottomLeft')[0];
var image = group.get('Image')[0];
var anchorX = activeAnchor.getX();
var anchorY = activeAnchor.getY();
// update anchor positions
switch (activeAnchor.getName()) {
case 'topLeft':
topRight.setY(anchorY);
bottomLeft.setX(anchorX);
break;
case 'topRight':
topLeft.setY(anchorY);
bottomRight.setX(anchorX);
break;
case 'bottomRight':
bottomLeft.setY(anchorY);
topRight.setX(anchorX);
break;
case 'bottomLeft':
bottomRight.setY(anchorY);
topLeft.setX(anchorX);
break;
}
image.position(topLeft.position());
var width = topRight.getX() - topLeft.getX();
var height = bottomLeft.getY() - topLeft.getY();
if (width && height) {
image.width(width);
image.height(height);
}
}
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
stage.add(layer);
// darth vader
var darthVaderImg = new Konva.Image({
width: 200,
height: 137,
name: 'imgs'
});
// yoda
var yodaImg = new Konva.Image({
width: 93,
height: 104,
name: 'imgs'
});
var darthVaderGroup = new Konva.Group({
x: 180,
y: 50,
draggable: true,
id: 'test1',
name: 'Imgs'
});
var num = 0;
function addCanvas() {
var test = new Konva.Group({
x: 200,
y: 100,
draggable: true
});
var testImg = new Konva.Image({
width: 93,
height: 104
});
layer.add(test);
test.add(testImg);
console.log('test');
var imageObjs = new Image();
imageObjs.onload = function() {
testImg.image(imageObjs);
layer.draw();
};
imageObjs.src = './pic/test2.png';
}
layer.add(darthVaderGroup);
darthVaderGroup.add(darthVaderImg);
var yodaGroup = new Konva.Group({
x: 20,
y: 110,
draggable: true,
id: 'Imgs',
});
layer.add(yodaGroup);
yodaGroup.add(yodaImg);
var imageObj1 = new Image();
imageObj1.onload = function() {
darthVaderImg.image(imageObj1);
layer.draw();
};
imageObj1.src = './pic/test2.png';
var imageObj2 = new Image();
imageObj2.onload = function() {
yodaImg.image(imageObj2);
layer.draw();
};
imageObj2.src = './pic/test1.jpg';
stage.on('click', function(e) {
if (e.target === stage) {
stage.find('Transformer').destroy();
layer.draw();
return;
}
// do nothing if clicked NOT on our rectangles
if (!e.target.hasName('imgs')) {
return;
}
// remove old transformers
// TODO: we can skip it if current rect is already selected
stage.find('Transformer').destroy();
// create new transformer
var tr = new Konva.Transformer();
layer.add(tr);
tr.attachTo(e.target);
layer.draw();
});
function addTrans(e) {
}
</script>
</body>
</html>
The output
Here's the output. Whenever I click the image the transform will be out of place and will on stay in 1 place.
I finally figure it out. Turn out I place the draggable in the wrong place. I put the draggable into the Konva.Image instead in the group.
Thanks

How to propagate a click event from a shape in the Upper layer to an image in the Lower Layer using KonvaJS?

Disclaimer: it may be considered this post is a duplicate of this post but I have demonstrated my need specifically.
I have a case in my KonvaJS application where I need to propagate a click event from the Rectangle shape (that is a child of the Upper Layer) to several images that are added to the Lower Layer.
Please note that I have in the Lower layer more than 50 objects between images and shapes, so how can I now what is the target object in the Lower Layer.
Kindly here is an example to demonstrate my need:
var width = window.innerWidth;
var height = window.innerHeight;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var lowerLayer = new Konva.Layer();
var upperLayer = new Konva.Layer();
//lion
var lionImage = new Image();
lionImage.onload = function() {
var lion = new Konva.Image({
x: 50,
y: 50,
image: lionImage,
width: 106,
height: 118
});
// add the shape to the layer
lowerLayer.add(lion);
stage.draw();
lion.on("click", function() {
alert("you clicked the lion");
});
};
lionImage.src = 'http://konvajs.github.io/assets/lion.png';
//monkey
var monkeyImage = new Image();
monkeyImage.onload = function() {
var monkey = new Konva.Image({
x: 200,
y: 50,
image: monkeyImage,
width: 106,
height: 118
});
// add the shape to the layer
lowerLayer.add(monkey);
stage.draw();
monkey.on("click", function() {
alert("you clicked the monkey");
});
};
monkeyImage.src = 'http://konvajs.github.io/assets/monkey.png';
var upperTransparentBox = new Konva.Rect({
x: 0,
y: 0,
height: stage.height(),
width: stage.width(),
fill: 'transparent',
draggable: false,
name: 'upperTransparentBox'
});
upperTransparentBox.on("click", function() {
alert("you clicked the upper Transparent Box");
});
upperLayer.add(upperTransparentBox);
// add the layer to the stage
stage.add(lowerLayer);
stage.add(upperLayer);
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.rawgit.com/konvajs/konva/1.0.2/konva.min.js"></script>
<meta charset="utf-8">
<title>Konva Image Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #F0F0F0;
}
</style>
</head>
<body>
<div id="container"></div>
</body>
</html>
Technically it is possible to manually trigger click event on any node.
But I think it is an antipattern. You can just find an intersection with 'getIntersection()' function and do what you need with a node.
var width = window.innerWidth;
var height = window.innerHeight;
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var lowerLayer = new Konva.Layer();
var upperLayer = new Konva.Layer();
//lion
var lionImage = new Image();
lionImage.onload = function() {
var lion = new Konva.Image({
x: 50,
y: 50,
name: 'lion',
image: lionImage,
width: 106,
height: 118
});
// add the shape to the layer
lowerLayer.add(lion);
stage.draw();
lion.on("click", function() {
alert("you clicked the lion");
});
};
lionImage.src = 'http://konvajs.github.io/assets/lion.png';
//monkey
var monkeyImage = new Image();
monkeyImage.onload = function() {
var monkey = new Konva.Image({
x: 200,
y: 50,
name: 'monkey',
image: monkeyImage,
width: 106,
height: 118
});
// add the shape to the layer
lowerLayer.add(monkey);
stage.draw();
monkey.on("click", function() {
alert("you clicked the monkey");
});
};
monkeyImage.src = 'http://konvajs.github.io/assets/monkey.png';
var upperTransparentBox = new Konva.Rect({
x: 0,
y: 0,
height: stage.height(),
width: stage.width(),
fill: 'transparent',
draggable: false,
name: 'upperTransparentBox'
});
upperTransparentBox.on("click", function() {
var target = lowerLayer.getIntersection(stage.getPointerPosition());
if (target) {
alert('clicked on ' + target.name());
}
});
upperLayer.add(upperTransparentBox);
// add the layer to the stage
stage.add(lowerLayer);
stage.add(upperLayer);
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.rawgit.com/konvajs/konva/1.0.2/konva.min.js"></script>
<meta charset="utf-8">
<title>Konva Image Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #F0F0F0;
}
</style>
</head>
<body>
<div id="container"></div>
</body>
</html>

kineticjs: rotate image by certain angle and stop

I'm completely new in HTML and kineticjs and I want to create an animation, which rotates an image around a certain point and by a certain angle. Then it has to stop.
Later I want to implement a way to control the angle by clicking a button. But to the first problem: This is the code so far:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.0.0.min.js"> </script>
<script defer="defer">
var stage = new Kinetic.Stage({
container: 'container',
width: 578,
height: 200
});
var layer = new Kinetic.Layer();
var imageObj = new Image();
imageObj.onload = function() {
var yoda = new Kinetic.Image({
x: 200,
y: 50,
image: imageObj,
width: 106,
height: 118,
//offset: [x:250, y: 100]
});
/*var imageObj2 = new Image();
imageObj.onload = function() {
var background = new Kinetic.Image({
x: 200,
y: 50,
image: imageObj,
width: 106,
height: 118,
}); */
// add the shape to the layer
layer.add(yoda);
//layer.add(background)
// add the layer to the stage
stage.add(layer);
var angularSpeed = 360 / 4;
var anim = new Kinetic.Animation(function(frame) {
var angleDiff = frame.timeDiff * angularSpeed / 1000;
yoda.rotate(angleDiff);
}, layer);
anim.start();
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/yoda.jpg';
//other image source
</script>
</body>
</html>
Source: http://www.html5canvastutorials.com/kineticjs/html5-canvas-kineticjs-image-tutorial/
So how can I make the animation stop after - say - 50°?
Thanks for your help!
You can use Tween:
var tweaktween = new Kinetic.Tween({
node : yoda,
rotation : 50,
duration: 1
});
tween.start();
demo: http://jsfiddle.net/lavrton/2DDtW/

HTML5 Canvas: how to have an image and a shape on the canvas and shape is Drag n Droppable?

I'm having trouble creating an HTML5 canvas in which a an image is present, a shape is present, and the shape is draggable on the same stage. My gut tells me that I need to create multiple layers or multiple stages/canvases. Then have one be regular and the other be Kinetic. I've found some code for draggable shapes, code for displaying images and shapes, and I think my problem only lies in the implementation of the syntax. Here's the code:
<!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 stage = new Kinetic.Stage({
container: "container",
width: 578,
height: 200
var layer = new Kinetic.Layer();
var rectX = stage.getWidth() / 2 - 50;
var rectY = stage.getHeight() / 2 - 25;
var box = new Kinetic.Rect({
x: rectX,
y: rectY,
width: 100,
height: 50,
fill: "#00D2FF",
stroke: "black",
strokeWidth: 4,
draggable: true
});
var layer1 = new Kinetic.Layer();
var imageObj = new Image();
imageObj.onload = function() {
var image = new Kinetic.Image({
x: stage.getWidth() / 2 - 53,
y: stage.getHeight() / 2 - 59,
image: imageObj,
width: 106,
height: 118
});
layer1.add(image);
stage.add(layer1);
// add cursor styling
box.on("mouseover", function() {
document.body.style.cursor = "pointer";
});
box.on("mouseout", function() {
document.body.style.cursor = "default";
});
layer.add(box);
stage.add(layer);
imageObj.src = "http://www.html5canvastutorials.com/demos/assets/yoda.jpg";
};
</script>
</head>
<body onmousedown="return false;">
<div id="container"></div>
</body>
</html>
Try this website: w3shools.com/html5/html5_draganddrop.asp

Categories

Resources