How do I change the style when feature is modifying and not stop the modify - styles

I want to change the style when the feature is modifying, but once the feature's style has been setting, its modify would be stopped, how can I change the style and it still can modify?
here is the code:
this.modify.on(['modifystart', 'modifyend'], function (evt) {
target.style.cursor = evt.type === 'modifystart' ? 'grabbing' : 'pointer'
const currentFeature = evt.features.array_[0]
const oldStyle = currentFeature.getStyle()
console.log(oldStyle)
console.log(evt.type)
if (evt.type === 'modifystart') {
const moveImage = new Image()
const pinInfo = evt.features.array_[0].get('pinInfo')
moveImage.src = that.moveIcon
moveImage.width = 50
moveImage.height = 70
moveImage.onload = function () {
const iconCanvas = document.createElement('canvas')
iconCanvas.width = moveImage.width
iconCanvas.height = moveImage.height
const iconCanvasCtx = iconCanvas.getContext('2d')
// 背景アイコンを描画
iconCanvasCtx.drawImage(moveImage, 0, -25, 50, 70)
const style = new Style({
image: new Icon({
anchor: [0.5, 0.5],
img: iconCanvas,
imgSize: [moveImage.width, moveImage.height],
scale: that.imgSize / 30
})
})
// const arrayStyle = [style, oldStyle]
currentFeature.setStyle(style)
}
} else if (evt.type === 'modifyend') {
// currentFeature.setStyle(oldStyle)
}
})
Thanks a lot!

Related

Button labels going wrong on pdf-lib capture using html2canvas

I am using pdf-lib to capture and html2canvas, but when the page is captured, Button labels, they go wrong. "Buy Again" becomes "BuyA Gain".
Also when I scroll the page, the page captured gets cut, when it should not because it is being captured on the basis of elementID
const onClickPrint = () => {
const domElement = document.getElementById(elementId);
var printButton = document.getElementById("printIcon");
printButton.style.visibility = "hidden";
var downloadButton;
try {
downloadButton = document.getElementById("downloadIcon");
downloadButton.style.visibility = "hidden";
} catch (e) { }
html2canvas(domElement).then((canvas) => {
(async () => {
const pdfDoc = await PDFDocument.create();
const imagePDF = await pdfDoc.embedPng(canvas.toDataURL("image/PNG"));
let height = imagePDF.height;
let width = imagePDF.width;
const page = pdfDoc.addPage([A4_PAGE.width, A4_PAGE.height]);
let widthRatio = A4_PAGE.width / width;
let heightRatio = A4_PAGE.height / height;
let ratio = widthRatio > heightRatio ? heightRatio : widthRatio;
page.drawImage(imagePDF, {
x: A4_PAGE.width / 2 - (width * ratio) / 2,
y: A4_PAGE.height / 2 - (height * ratio) / 2,
width: width * ratio,
height: height * ratio,
});
const pdfBytes = await pdfDoc.save();
const blob = new Blob([pdfBytes], { type: "application/pdf" });
openPrintDialog(blob);
})();
});
printButton.style.visibility = "visible";
if (downloadButton != null) {
downloadButton.style.visibility = "visible";
}
};

How to find missing font glyphs using node canvas?

I am trying to find missing glyphs with node canvas by comparing the rendered glyph with a known missing glyph, but it's not working. Any ideas?
const { createCanvas, loadImage } = require('canvas')
const fs = require('fs')
const testCanvas = createCanvas(200, 200)
const referenceCanvas = createCanvas(200, 200)
const ctxTest = testCanvas.getContext('2d')
const ctxRef = referenceCanvas.getContext('2d')
ctxRef.fillText('𠆼', 0, 0)
const refData = ctxRef.getImageData(0, 0, referenceCanvas.width, referenceCanvas.height).data.join('')
fs.readFileSync('path-to-chars.txt', 'utf-8').trim()
.split(/\n+/)
.filter(x => x.startsWith('U+'))
.map(x => {
let [a, b, c] = x.split(/\t/)
let q = String.fromCodePoint(parseInt(a.replace('U+', ''), 16))
if (test(q)) {
console.log('skip', a, q)
return
}
c.match(/\^([^\$]+)\$/)
const fullText = RegExp.$1
const radicals = [...fullText.replace(/[⿰⿱⿲⿳⿴⿵⿶⿷⿸⿹⿺⿻]/g, '').replace(/\{[^\}]+\}/g, '')]
for (let i = 0, n = radicals.length; i < n; i++) {
const char = radicals[i]
if (test(char)) return
}
console.log(radicals, radicals.map(x => x.codePointAt(0).toString(16)))
return q
})
function test(char) {
ctxTest.clearRect(0, 0, testCanvas.width, testCanvas.height)
ctxTest.fillText(char, 0, 0)
const testData = ctxTest.getImageData(0, 0, testCanvas.width, testCanvas.height).data.join('')
console.log(char, testData === refData)
return testData === refData
}
I don't know what ones are missing in advance. I am just trying to filter them out.

Convert SVG to PNG and download, vue 2

I'm looking for a clean way to convert a SVG to PNG and download, in Vue 2. What is the best approach ?
I finally managed to come up with this solution:
save() {
const a = document.querySelector("a");
const triggerDownload = (imgURI: string) => {
const evt = new MouseEvent("click", {
view: window,
bubbles: false,
cancelable: true,
});
a?.setAttribute("download", "FileName.png");
a?.setAttribute("href", imgURI);
a?.setAttribute("target", "_blank");
a?.dispatchEvent(evt);
};
const canvas = document.getElementById("canvas") as HTMLCanvasElement;
const ctx = canvas.getContext("2d");
data = new XMLSerializer().serializeToString(
document.getElementById("svgId") as Node
);
const DOMURL = window.URL || window.webkitURL || window;
const img = new Image();
const svgBlob = new Blob([data], { type: "image/svg+xml;charset=utf-8" });
const url = DOMURL.createObjectURL(svgBlob);
img.onload = function () {
ctx?.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
const imgURI = canvas
.toDataURL("image/png")
.replace("image/png", "image/octet-stream");
triggerDownload(imgURI);
ctx?.clearRect(0, 0, canvas.width, canvas.height);
};
img.src = url;
},

Adding image dynamically in public folder in reactjs

I am developing an face detection application,for that I need to collect the users image for reference to detect them later.i have successfully uploaded the image in MySQL databse.now I need upload the image in public folder in react to detect the image in camera.i stuck in uploading image in react public folder.help me out get rid of this problem..
This is the React code where image to be detected in the imgUrl variable
detect = async () => {
const videoTag = document.getElementById("videoTag");
const canvas = document.getElementById("myCanvas");
const displaySize = { width: videoTag.width, height: videoTag.height };
faceapi.matchDimensions(canvas, displaySize);
//setInterval starts here for continuous detection
time = setInterval(async () => {
let fullFaceDescriptions = await faceapi
.detectAllFaces(videoTag)
.withFaceLandmarks()
.withFaceExpressions()
.withFaceDescriptors();
const value = fullFaceDescriptions.length;
this.setState({ detection: value });
fullFaceDescriptions = faceapi.resizeResults(
fullFaceDescriptions,
displaySize
);
canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
//Label Images
var dummy = ["praveen", "vikranth", "Gokul", "Rahul"];
const labels = nameArray1;
// const labels = ["praveen", "vikranth", "Gokul", "Rahul"];
if (no_of_times <= 0) {
if (no_of_times === 0) {
labeledFaceDescriptors = await Promise.all(
labels.map(async (label) => {
// fetch image data from urls and convert blob to HTMLImage element
const imgUrl = `/img/${label}.png`; // for testing purpose
// const imgUrl = testImage;
const img = await faceapi.fetchImage(imgUrl);
const fullFaceDescription = await faceapi
.detectSingleFace(img)
.withFaceLandmarks()
.withFaceExpressions()
.withFaceDescriptor();
if (!fullFaceDescription) {
throw new Error(`no faces detected for ${label}`);
}
const faceDescriptors = [fullFaceDescription.descriptor];
return new faceapi.LabeledFaceDescriptors(label, faceDescriptors);
})
);
// console.log(no_of_times);
}
}
const maxDescriptorDistance = 0.7;
no_of_times++;
const faceMatcher = new faceapi.FaceMatcher(
labeledFaceDescriptors,
maxDescriptorDistance
);
const results = fullFaceDescriptions.map((fd) =>
faceMatcher.findBestMatch(fd.descriptor)
);
result = [];
results.forEach((bestMatch, i) => {
const box = fullFaceDescriptions[i].detection.box;
// console.log(box)
const text = bestMatch.toString(); //this for basMatch name detection
var str = "";
//This is for removing names confidence to map value without duplicate
var val = text.replace(/[0-9]/g, "");
for (let i of val) {
if (i !== " ") {
str += i;
} else {
break;
}
}
if (result.includes(str) === false) result.push(str);
const drawBox = new faceapi.draw.DrawBox(box, { label: text });
drawBox.draw(canvas);
faceapi.draw.drawFaceExpressions(canvas, fullFaceDescriptions, 0.85);
});
for (let i = 0; i < fullFaceDescriptions.length; i++) {
const result1 = fullFaceDescriptions[i].expressions.asSortedArray()[i];
// console.log(result[i]);
// console.log(result1.expression);
this.test(result[i], result1.expression);
}
}, 100);
In the above code i am manually putting image in public folder,this need to be done dynamically when the user uploads image.
this is place i get the images in base64 from nodejs
axios.get("/image").then((res) => {
testImage = res.data;
// console.log("from image" + res.data);
imgback = <img src={`data:image/jpeg;base64,${res.data}`} />;
});
This is nodejs code for the get request from reactjs
app.get("/image", (req, res) => {
connection.query("SELECT * FROM images", (error, row, fields) => {
if (!!error) {
console.log("Error in the query");
} else {
console.log("successful query");
var buffer = new Buffer(row[0].image, "binary");
var bufferBase64 = buffer.toString("base64");
res.send(bufferBase64);
}
});
});
my goal is, in the imgUrl variable in react code i need to specify the image folder for that i need to dynamically add image in folder.
Or is there is any other way to directly give image array in the imgUrl variable.please help me to sort out this problem.

Using electron to show value on touch bar slider

I would like to show the value from the TouchBarSlider according to where I move it to. An example example of TouchBar can be followed here. I still cannot figure out how to display the value using their given method change from TouchBarSlider.
My current main.js looks like the following.
const {app, BrowserWindow, TouchBar} = require('electron')
const {TouchBarLabel, TouchBarSlider} = TouchBar
const slider = new TouchBarSlider({label: 'angle',
minValue: 0,
maxValue: 360})
const result = new TouchBarLabel()
result.label = '30' + ' deg';
const updateBar = () => {
let timeout = 100;
if (slider.change()){
result.label = slider.values.toString() + ' deg'
}
setTimeout(updateBar, timeout)
}
const touchBar = new TouchBar([
slider, // add slider
result // add display for slider value but doesn't work yet
])
let window;
app.once('ready', () => {
window = new BrowserWindow({
width: 300,
height: 200
});
window.loadURL('about:blank')
window.setTouchBar(touchBar);
})
// Quit when all windows are closed and no other one is listening to this.
app.on('window-all-closed', () => {
app.quit();
});
I also have example repository here. You can just replace my given main.js in the project in order to try things out. My electron version is 1.6.4 and node version is 7.4.0
const { app, BrowserWindow, TouchBar } = require('electron');
const path = require('path')
const url = require('url')
const {TouchBarButton, TouchBarLabel, TouchBarSlider} = TouchBar
const result = new TouchBarLabel();
result.label = '30' + ' deg';
const slider = new TouchBarSlider({
label: 'angle',
minValue: 0,
maxValue: 360,
change: (val) => result.label = val.toString() + ' deg' // register event handler here!
});
const touchBar = new TouchBar([
slider, // add slider
result // add display for slider value
]);
let window;
app.once('ready', () => {
window = new BrowserWindow({
width: 300,
height: 200
});
window.loadURL('about:blank');
window.setTouchBar(touchBar);
});
// Quit when all windows are closed and no other one is listening to this.
app.on('window-all-closed', () => {
app.quit();
});
Working code. Hope this helps! ;)

Resources