Konva How to display images from array - konvajs

can you please help me?
i am trying to display png Images from an PHP array (with x y psoition preset) into the container/canvas. But have not found any sample showing that. All images appear on the same position. Then I want the pngs to be dragged and dropped some whre else in the canvas.
Your input is very much appreciated.
Best Regards

I hope I understood the problem correctly.
<?php foreach($images as $image) : ?>
var imageObj = new Image();
imageObj.onload = function() {
var image = new Konva.Image({
x: <?php echo $image->x ?>,
y: <?php echo $image->y ?>,
image: imageObj,
width: 100,
height: 100
});
};
imageObj.src = <?php echo $image->source ?>
<?php endforeach ?>

Related

Multiple html2canvas div content in single .pdf file

I'm using attached script to allocate content of div into .pdf file with jsPDF and html2canvas.
All works nicely with content of one single div (inputdiv).
However, I would like to add conent from few more additional div's into same .pdf file.
Question is how to do that?
With approach from below, only content of single div can be mapped through relevant canvas function. I tried to find some extra details in documentation and also here but unfortunately without success.
Any reference would be highly appreciated!
function generatePDF() {
var doc = new jsPDF ("l", "mm", "a4", "true");
html2canvas(inputdiv, {
width: 2000,
height: 1450,
scale: 2,
onclone: function (clonedDoc) {
clonedDoc.getElementById('inputdiv').style.display = 'block';
}
})
.then(function(canvas) {
var imgData = canvas.toDataURL('image/jpeg',1.0);
const imgProps= doc.getImageProperties(imgData);
const pdfWidth = doc.internal.pageSize.getWidth();
const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
doc.addImage(imgData, 'jpeg', 14, 19, pdfWidth, pdfHeight, undefined, 'FAST');
doc.save('File.pdf');
});
}
This is an example of how you can solve this, for 2 divs that will print on 2 pages.
Of course if you have many divs, it would need to be refactored to avoid code repetition; but this one worked for me to include 2 different divs.
html2canvas(div1)
.then((canvasDiv1) =>{
//...
pdf.addImage(/* ... */);
})
.then(() => {
pdf.addPage();
html2canvas(div2)
.then((canvasDiv2) => {
//...
pdf.addImage(/* ... */);
// save on the last element
pdf.save(/* ... */);
})
})
If you need both divs to be on the same page, then just remove the pdf.addPage() and adjust the coordinates to place the second div where you need.

Konva converting stage toDataUrl() do not work in chrome browser,but work well in safari browser

I have Konva Stage with few layers, when I try convert to image all stage - result is OK in safari browser , when I try convert stage in chrome ,firefox etc. - result is failed. I think that toDataUrl() method does
not work well in chrome browser ,firefox browser etc except for safari browser
<button id="save" type="button">save</button>
<div id="container"></div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;
function downloadURI(uri, name) {
var link = document.createElement('a');
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
}
function drawImage(imageObj) {
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
// darth vader
var darthVaderImg = new Konva.Image({
image: imageObj,
x: stage.getWidth() / 2 - 200 / 2,
y: stage.getHeight() / 2 - 137 / 2,
width: 200,
height: 137,
name: 'myimg',
draggable: true
});
// add cursor styling
darthVaderImg.on('mouseover', function () {
document.body.style.cursor = 'pointer';
});
darthVaderImg.on('mouseout', function () {
document.body.style.cursor = 'default';
});
layer.add(darthVaderImg);
stage.add(layer);
stage.on('click tap', function (e) {
// if click on empty area - remove all transformers
if (e.target === stage) {
stage.find('Transformer').destroy();
layer.draw();
return;
}
// do nothing if clicked NOT on our rectangles
if (!e.target.hasName('myimg')) {
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();
})
document.getElementById('save').addEventListener(
'click',
function () {
var dataURL = stage.toDataURL({ pixelRatio: 3 });
downloadURI(dataURL, 'stage.png');
},
false
);
}
var imageObj = new Image();
imageObj.onload = function () {
drawImage(this);
};
imageObj.src = 'https://www.decanterchina.com/assets/images/article/550/136031_decanter-cava-tasting-1.jpg';
</script>
Any possible reasons or solutions ? Thanks!!
If you look into the console you will see a message:
Konva warning: Unable to get data URL. Failed to execute 'toDataURL'
on 'HTMLCanvasElement': Tainted canvases may not be exported.
You have CORS issue. Take a look here for solutions:
Tainted canvases may not be exported
https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image

How to use phpthumb in phx:tv?

Using MODX Evo 1.0.7
I am using phx:tv in a chunk like this:
[+phx:tv=`14?Photo`+]
Here is the phx:tv snippet (Source: http://wiki.modxcms.com/index.php/PHx/CustomModifiers#phx:tv)
<?php
if(strlen($options )>0) {
$data = explode("?",trim($options),2);
$id= (!empty($data[0]) && is_numeric($data[0])) ? $data[0]: '';
$tv= (!empty($data[1])) ? $data[1]: '';
$result = $modx->getTemplateVar($tv, 'name', $id, 1);
return $result['value'];
}
?>
How can I use the phpthumb to resize the image in the Photo TV in the code?
I haven't used phx or Evo for a long time, but you might try chaining it like this:
[+phx:tv=`14?Photo`:phpthumb=`w=450`+]

dojox.gfx - Maintaining gfx references for event connection

I have a simple program where I am GETing an svg file and then creating gfx shapes from rect elements within the svg as follows
function superCallback(shape){
shape.setFill("red");
}
dojo.ready(function() {
// Load image
dojo.xhrGet({
//handleAs: 'xml',
url: 'svg/demo.svg',
load: function(data) {
// Create the surface
var surface = dojox.gfx.createSurface("logoHolder", 2000, 1500);
var group = surface.createGroup();
var dom = dojox.xml.parser.parse(data);
rects = dom.getElementsByTagName("rect");
for (var idx = 0 ; idx < rects.length ; idx++) {
//alert('Coordinates ' + rects[idx].getAttribute("x") + ', ' + rects[idx].getAttribute("y"));
var rectangle = group.createRect({ x: parseFloat(rects[idx].getAttribute("x")),
y: parseFloat(rects[idx].getAttribute("y")),
width: parseFloat(rects[idx].getAttribute("width")),
height: parseFloat(rects[idx].getAttribute("height")) })
.setStroke({ style: "Solid" , width: "7" , color :"black"});
rectangle.connect("onclick",dojo.hitch(rectangle,function(e) {
superCallback(rectangle);
}));
}
});
});
As can be seen, I am using a local variable rectangle to create and store the gfx shape and then calling connect to attach an event to it.
The problem is that the event is attached to only the last gfx rect which is created in teh for loop because I guess the closure is executing in the context of the last rectangle reference always.
Need some help in fixing this so that all rects can be triggered by the event
Thanks in advance
Regards
Shyam

Inaccurate results from ImageMagick function queryFontMetrics

Imagick::queryFontMetrics does not seem to be working. When I use the metrics provided by queryFontMetrics to size the image, some fonts are still being cut off. Any ideas?
Here's my code:
if (!file_exists($cache['dirname'].'/'.$cache['basename'])) {
try {
$draw = new ImagickDraw();
$draw->setFont($font_path['dirname'].'/'.$font_path['basename']);
$draw->setFontSize($size);
$draw->setGravity(Imagick::GRAVITY_CENTER);
$draw->setFillColor($color);
$canvas = new Imagick();
$metrics = $canvas->queryFontMetrics($draw, $text);
$canvas->newImage($metrics['textWidth'], $metrics['textHeight'], "transparent", "png");
$canvas->annotateImage($draw, 0, 0, 0, $text);
$canvas->setImageFormat('PNG');
mkdir($cache['dirname'], 0777, true);
$canvas->writeImage($cache['dirname'].'/'.$cache['basename']);
header("Content-Type: image/png");
echo $canvas;
$canvas->clear();
$canvas->destroy();
$draw->clear();
$draw->destroy();
} catch(Exception $e) {
// Output an error message
echo 'Error: ', $e->getMessage(), "";
}
} else {
// Output the image
$canvas = new Imagick($cache['dirname'].'/'.$cache['basename']);
header("Content-Type: image/png");
echo $canvas;
}
Okay, it looks like I'll be answering this one myself. After quite a bit of research, I've discovered that it's basically impossible to get correct metrics from the font itself. This is because each font designer could potentially define the metrics differently. The best way to proceed is to simply make the image much larger than necessary (to ensure that no clipping occurs) and then use the trim command: http://www.php.net/manual/en/imagick.trimimage.php.

Resources