Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 months ago.
Improve this question
how to fix await with forEach
const url = await Canvas.loadImage(getvalueof.displayAvatarURL( { format: "png", dynamic: true } ))
^^^^^
SyntaxError: await is only valid in async functions and the top level bodies of modules
client.on('voiceStateUpdate' , (Old,New) => {
if(New.bot) return;
if(Old.bot) return;
if(New.channelId == voiceID) {
New.guild.members.cache.filter(m => m.roles.cache.get("1026253368198451270")).forEach(async sa => {
console.log("hi");
const w = ['4Skysupport.png'];
let Image = Canvas.Image,
canvas = new Canvas.createCanvas(1280, 720),
ctx = canvas.getContext('2d');
ctx.patternQuality = 'bilinear';
ctx.filter = 'bilinear';
ctx.antialias = 'subpixel';
ctx.shadowColor = 'rgba(0, 0, 0, 0.4)';
ctx.shadowOffsetY = 2;
ctx.shadowBlur = 2;
fs.readFile(`${w[Math.floor(Math.random() * w.length)]}`, function (err, Background) {
if (err) return console.log(err);
const BG = Canvas.Image;
const ground = new Image;
ground.src = Background;
let user = New.member.user;
var men = New.member.user;
var heg;
if(men) {
heg = men
} else {
heg = New.member.user;
}
var mentionned = New.member.user;
var h;
if(mentionned) {
h = mentionned
} else {
h = New.member.user;
}
var ment = New.member.user;
var getvalueof;
if(ment) {
getvalueof = New.member.user;
} else {
getvalueof = New.member.user;
}
const url = await Canvas.loadImage(getvalueof.displayAvatarURL( { format: "png", dynamic: true } ))
// Small Avatar
let Avatar = Canvas.Image;
let ava1 = new Avatar;
ava1.src = url;
ctx.beginPath();
ctx.arc(400, 400, 0, 2 * Math.PI);
ctx.drawImage(ava1, 450, 601, 80, 70);
ctx.restore();
ctx.font = '35px Arial Bold';
ctx.fontSize = '40px';
ctx.fillStyle = "#dadada";
ctx.textAlign = "center";
//background
ctx.drawImage(ground, 0, 0, 1280, 720);
var ment1 = sa.user;
var getvalueof1;
if(ment1) {
getvalueof1 = sa.user;
} else {
getvalueof1 = sa.user;
}
const url1 = await Canvas.loadImage(getvalueof1.displayAvatarURL( { format: "png", dynamic: true } ))
// Avatar
let Avatar1 = Canvas.Image;
let ava = new Avatar1;
ava.src = url1;
ctx.beginPath();
ctx.drawImage(ava, 488, 50, 260, 250);
ctx.font = '35px Arial Bold';
ctx.fontSize = '40px';
ctx.fillStyle = "#dadada";
ctx.textAlign = "center";
ctx.beginPath();
ctx.stroke();
sa.send({files: [canvas.toBuffer()]});
})
})
}
});
for await is supposed to be used with asynchronous iterators
for await (const res of items.map(e => somethingAsync(e))) …
instead of
New.guild.members.cache.filter(m => m.roles.cache.get("1026253368198451270")).forEach(async sa =>
you can use
for await (const res of New.guild.members.cache.filter(m => m.roles.cache.get("1026253368198451270"))) …
Related
my Image is the and code is here i want to make nameplate of text. This is scorolble panel.
const updatePanel = (panel, content) => {
const sizer = panel.getElement("panel");
const { scene } = panel;
var nameImage, nameText;
sizer.clear(true);
const lines = content.split("\n");
for (let li = 0, lcnt = lines.length; li < lcnt; li += 1) {
const words = lines[li].split(" ");
for (let wi = 0, wcnt = words.length; wi < wcnt; wi += 1) {
nameText = sizer.add(
scene.add
.text(0, 0, words[wi], {
fontSize: 20,
fill: "#f4b331",
})
.setInteractive()
.on("pointerdown", () => {
// this.scene.print.text = this.text;
// this.setTint(Phaser.Math.Between(0, 0xf4b331));
})
);
console.log("new line")
}
if (words != '' && content != "Loading...") {
nameImage = sizer.add(scene.add.sprite(0, 0, "nameplate"));
}
if (li < lcnt - 1) {
sizer.addNewLine();
}
}
panel.layout();
return panel;
};
my Image is the and code is here i want to make nameplate of text. This is scorolble panel.
const updatePanel = (panel, content) => {
const sizer = panel.getElement("panel");
const { scene } = panel;
var nameImage, nameText;
sizer.clear(true);
const lines = content.split("\n");
for (let li = 0, lcnt = lines.length; li < lcnt; li += 1) {
const words = lines[li];
for (let wi = 0, wcnt = words.length; wi < wcnt; wi += 1) {
}
sizer.add(
scene.add
.text(0, 0, ' ', {
fontSize: 20,
fill: "#f4b331",
})
);
if (words != '' && content != "Loading...") {
nameImage = sizer.add(
new ScoreBg(
scene,
0,
0,
"nameplate",
"nameplate",
words,
"",
"",
"#f4b331"
)
// scene.add.sprite(0, 0, "nameplate"),
);
// nameImage
}
if (li < lcnt - 1) {
sizer.addNewLine();
}
}
panel.layout();
return panel;
};
I'm trying to add AnalyserNode and visualize the output sound to a web audio example that I made but I can't figure out how. I think I am not passing the right source to the analyser (?)
Here for the full code : https://jsfiddle.net/kepin95043/1ub0sjo3/
<script>
var fs = 2000;
var gain = 0.2;
class Sound {
constructor(context) {
this.context = context;
}
init() {
this.oscillator = this.context.createOscillator();
this.oscillator.frequency.value = fs;
this.gainNode = this.context.createGain();
this.oscillator.connect(this.gainNode);
this.gainNode.connect(this.context.destination);
}
play(value) {
this.init();
this.gainNode.gain.setValueAtTime(gain, this.context.currentTime);
this.oscillator.start();
}
stop() {
this.gainNode.gain.exponentialRampToValueAtTime(0.001, this.context.currentTime + 1);
this.oscillator.stop(this.context.currentTime + 1);
}
}
var context = new AudioContext();
var sound = new Sound(context);
sound.init();
var wave = 'sine';
var state = 'paused';
var waveSelectors = document.querySelectorAll('.waveform');
var playBtn = document.querySelector('#play');
var container = document.querySelector('.container');
waveSelectors.forEach(function(button) {
button.addEventListener('click', function() {
cleanClass('active');
wave = button.dataset.wave;
sound.oscillator.type = wave;
button.classList.add('active');
})
})
playBtn.addEventListener('click', function() {
context.resume().then(() => {
console.log('Playback resumed successfully');
});
if (playBtn.text == 'Play') {
sound.play();
sound.oscillator.type = wave;
playBtn.text = 'Pause';
} else {
sound.stop();
playBtn.text = 'Play';
}
})
function cleanClass(rclass) {
waveSelectors.forEach(function(button) {
button.classList.remove(rclass);
})
}
function changeFs(val) {
fs = val;
var output = document.getElementById("fsValue");
output.innerHTML = val;
sound.stop();
sound.play();
console.log(val);
};
function changeGain(val) {
gain = val;
var output = document.getElementById("gainValue");
output.innerHTML = val;
sound.stop();
sound.play();
console.log(val);
};
var masterGain;
masterGain = context.createGain();
masterGain.connect(context.destination);
// analyser
var analyser = context.createAnalyser();
masterGain.connect(analyser);
var waveform = new Float32Array(analyser.frequencyBinCount);
analyser.getFloatTimeDomainData(waveform);
(function updateWaveform() {
requestAnimationFrame(updateWaveform);
analyser.getFloatTimeDomainData(waveform);
}());
var spectrum = new Uint8Array(analyser.frequencyBinCount);
(function updateSpectrum() {
requestAnimationFrame(updateSpectrum);
analyser.getByteFrequencyData(spectrum);
}());
// oscilloscope
var scopeCanvas = document.getElementById('canvas');
scopeCanvas.width = waveform.length;
//scopeCanvas.height = 200;
scopeCanvas.height = scopeCanvas.width * 0.33;
var scopeContext = scopeCanvas.getContext('2d');
(function drawOscilloscope() {
requestAnimationFrame(drawOscilloscope);
scopeContext.clearRect(0, 0, scopeCanvas.width, scopeCanvas.height);
scopeContext.strokeStyle="white"; // Green path
scopeContext.beginPath();
for (var i = 0; i < waveform.length; i++) {
var x = i;
var y = (0.5 + waveform[i] / 2) * scopeCanvas.height;
if (i === 0) {
scopeContext.moveTo(x, y);
} else {
scopeContext.lineTo(x, y);
}
}
scopeContext.stroke();
}());
</script>
Could anyone help me to identify what I'm doing wrong?
Thank in advance!
PS: Open it with Firefox. Does not work on Chromium based browsers for me.
Here is a working example: https://codepen.io/dennisgaebel/pen/YEwLaL
You create a Sound object and also a masterGain that is connected to your AnalyserNode. But I don't see where the sound ever connects to the masterGain. Without that, your analyser node just gets silence.
Here is the full working script code:
var fs = 2000;
var gain = 0.2;
class Sound {
constructor(context) {
this.context = context;
}
init() {
this.oscillator = this.context.createOscillator();
this.oscillator.frequency.value = fs;
this.gainNode = this.context.createGain();
this.oscillator.connect(this.gainNode);
this.gainNode.connect(this.context.destination);
}
play(value) {
this.init();
this.gainNode.gain.setValueAtTime(gain, this.context.currentTime);
this.oscillator.start();
// connect analyser to the gainedSource
this.gainNode.connect(analyser);
// for the non gainedSource
//this.gainNode.connect(analyser);
}
stop() {
this.gainNode.gain.exponentialRampToValueAtTime(0.001, this.context.currentTime + 1);
this.oscillator.stop(this.context.currentTime + 1);
}
}
var context = new AudioContext();
var sound = new Sound(context);
sound.init();
var wave = 'sine';
var state = 'paused';
var waveSelectors = document.querySelectorAll('.waveform');
var playBtn = document.querySelector('#play');
var container = document.querySelector('.container');
waveSelectors.forEach(function(button) {
button.addEventListener('click', function() {
cleanClass('active');
wave = button.dataset.wave;
sound.oscillator.type = wave;
button.classList.add('active');
})
})
playBtn.addEventListener('click', function() {
context.resume().then(() => {
console.log('Playback resumed successfully');
});
if (playBtn.text == 'Play') {
sound.play();
sound.oscillator.type = wave;
playBtn.text = 'Pause';
} else {
sound.stop();
playBtn.text = 'Play';
}
})
function cleanClass(rclass) {
waveSelectors.forEach(function(button) {
button.classList.remove(rclass);
})
}
function changeFs(val) {
fs = val;
var output = document.getElementById("fsValue");
output.innerHTML = val;
sound.stop();
sound.play();
console.log(val);
};
function changeGain(val) {
gain = val;
var output = document.getElementById("gainValue");
output.innerHTML = val;
sound.stop();
sound.play();
console.log(val);
};
// analyser node
var analyser = context.createAnalyser();
var waveform = new Float32Array(analyser.frequencyBinCount);
analyser.getFloatTimeDomainData(waveform);
(function updateWaveform() {
requestAnimationFrame(updateWaveform);
analyser.getFloatTimeDomainData(waveform);
}());
var spectrum = new Uint8Array(analyser.frequencyBinCount);
(function updateSpectrum() {
requestAnimationFrame(updateSpectrum);
analyser.getByteFrequencyData(spectrum);
}());
// oscilloscope
var scopeCanvas = document.getElementById('canvas');
scopeCanvas.width = waveform.length;
scopeCanvas.height = scopeCanvas.width * 0.33;
var scopeContext = scopeCanvas.getContext('2d');
(function drawOscilloscope() {
requestAnimationFrame(drawOscilloscope);
scopeContext.clearRect(0, 0, scopeCanvas.width, scopeCanvas.height);
scopeContext.strokeStyle = "white"; // Green path
scopeContext.beginPath();
for (var i = 0; i < waveform.length; i++) {
var x = i;
var y = (0.5 + waveform[i] / 2) * scopeCanvas.height;
if (i === 0) {
scopeContext.moveTo(x, y);
} else {
scopeContext.lineTo(x, y);
}
}
scopeContext.stroke();
}());
const initMap = React.useCallback(defaultLayers => {
let lat = -6;
let lng = 100;
let zoom = 20;
areaMapRef.current = new window.H.Map(
mapContainerRef.current,
defaultLayers.vector.normal.map,
{
zoom,
center: { lng, lat }
}
);
window.addEventListener("resize", areaMapRef.current.getViewPort().resize);
behaviourRef.current = new window.H.mapevents.Behavior(
new window.H.mapevents.MapEvents(areaMapRef.current)
);
uiRef.current = window.H.ui.UI.createDefault(
areaMapRef.current,
defaultLayers
);
}, []);
React.useEffect(() => {
const platform = new window.H.service.Platform({
apikey: "MYAPIKEY"
});
const defaultLayers = platform.createDefaultLayers();
initMap(defaultLayers);},
[initMap]);
Above is my code, However, I am getting an Error:-
‘Parsing Error: The keyword ‘await’ is reserved’
The line where my Error is occurring is below. Help me if you can please.
I get the error of the first line of this bit of code
if you can help, it'd be greatly appreciated as I am struggling a lot with this issue. Thank you again!
const { body: buffer } = await snekfetch.get(member.user.displayAvatarURL);
const avatar = await Canvas.loadImage(buffer);
ctx.drawImage(avatar, 25, 25, 200, 200);
if (!channel) return;
const canvas = Canvas.createCanvas(700, 250);
const ctx = canvas.getContext('2d');
const { body:buf } = await snekfetch.get('https://cdn.glitch.com/6ec6dccb-f1a9-4c03-b4f1-d6c639e188c9%2Fwallpaper.jpg?1532779841254');
const background = await Canvas.loadImage(buffer);
ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
ctx.strokeStyle = '#74037b';
ctx.strokeRect(0, 0, canvas.width, canvas.height);
// Slightly smaller text placed above the member's display name
ctx.font = '28px sans-serif';
ctx.fillStyle = '#ffffff';
ctx.fillText('Welcome to the server,', canvas.width / 2.5, canvas.height / 3.5);
// Add an exclamation point here and below
ctx.font = applyText(canvas, `${member.displayName}!`);
ctx.fillStyle = '#ffffff';
ctx.fillText(`${member.displayName}!`, canvas.width / 2.5, canvas.height / 1.8);
ctx.beginPath();
ctx.arc(125, 125, 100, 0, Math.PI * 2, true);
ctx.closePath();
ctx.clip();
const { body: buffer } = await snekfetch.get(member.user.displayAvatarURL);
const avatar = await Canvas.loadImage(buffer);
ctx.drawImage(avatar, 25, 25, 200, 200);
const attachment = new Discord.Attachment(canvas.toBuffer(), 'welcome-image.png');
channel.send(`Welcome to the server, ${member}!`, attachment);
});
ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
ctx.strokeStyle = '#74037b';
ctx.strokeRect(0, 0, canvas.width, canvas.height);
// Slightly smaller text placed above the member's display name
ctx.font = '28px sans-serif';
ctx.fillStyle = '#ffffff';
ctx.fillText('Welcome to the server,', canvas.width / 2.5, canvas.height / 3.5);
// Add an exclamation point here and below
ctx.font = applyText(canvas, `${member.displayName}!`);
ctx.fillStyle = '#ffffff';
ctx.fillText(`${member.displayName}!`, canvas.width / 2.5, canvas.height / 1.8);
ctx.beginPath();
ctx.arc(125, 125, 100, 0, Math.PI * 2, true);
ctx.closePath();
ctx.clip();
const { body: buffer } = await snekfetch.get(member.user.displayAvatarURL);
const avatar = await Canvas.loadImage(buffer);
ctx.drawImage(avatar, 25, 25, 200, 200);
const attachment = new Discord.Attachment(canvas.toBuffer(), 'welcome-image.png');
channel.send(`Welcome to the server, ${member}!`, attachment);
});
await is only valid inside an async function. I can't see the function definition from the code you have posted but my first guess would be that it is a plain old function.
eg. if your code looks like:
function main() {
// ...code
const { body: buffer } = await snekfetch.get(member.user.displayAvatarURL);
// ...code
}
then you'll have problems, you need the async keyword before the function keyword
If you were to be trying to use arrow functions, a similar requirement would be in place:
const main = async () => {
// code...
const {body: buffer} = await snekfetch.get(member.user.displayAvatarURL);
// more code...
}
Also a note that the async keyword applies only to the function it is immediately attached to, not recursively down to every function that you define inside that function. So for instance, you could NOT do:
const main = async () => {
// code...
const getAvatar = () => {
const {body: buffer} = await snekfetch.get(member.user.displayAvatarURL);
};
// more code...
}
That would be a syntax error because await is used inside a function which was not declared as async, instead you would need to do:
const main = () => {
// code...
const getAvatar = async () => {
const {body: buffer} = await snekfetch.get(member.user.displayAvatarURL);
};
// more code...
}
But the problem is iam not able to rotate the sprite image based on user interaction.for eg: when the user moves the mouse on right the frame on right side should moved and when the user moves on left the left side of the frames should me moved iam not able to implement this in fabric js. What i have done is just rotating the sprite image onmouse move.Expected output i want is like this :https://codyhouse.co/demo/360-degrees-product-viewer/index.html
var URL = 'https://codyhouse.co/demo/360-degrees-product-viewer/img/alfa.png';
var canvas = new fabric.Canvas('canvas');
var positions = {
topSteps: 1,
leftSteps: 16
};
var y = 0;
var x = 0;
var topStep;
var leftStep;
canWalk(URL, positions);
function canWalk(URL, positions) {
var myImage = new Image();
myImage.src = URL;
//var mDown = false;
//onloadevent
myImage.onload = function () {
topStep = myImage.naturalHeight / positions.topSteps;
leftStep = myImage.naturalWidth / positions.leftSteps;
var docCanvas = document.getElementById('canvas');
docCanvas.height = topStep;
docCanvas.width = leftStep;
fabricImageFromURL(x, y);
};
}
//mouseevents
canvas.on('mouse:out', function (event) {
console.log("mouseout")
/* x=0;
y=0;
fabricImageFromURL(x,y);*/
});
canvas.on('mouse:move', function (event) {
resetvalue();
setTimeout(function () {
console.log('value of x in start', x)
console.log('positions.leftSteps', positions.leftSteps)
if (x == positions.leftSteps) {
y = 1;
fabricImageFromURL(-y * topStep, -x * leftStep)
}
else {
fabricImageFromURL(-y * topStep, -x * leftStep)
if (x < positions.leftSteps) {
x++;
}
}
}, 50);
});
function resetvalue() {
if (x == positions.leftSteps) {
x = 0;
y = 0;
console.log("x and y value reset to0")
}
}
function fabricImageFromURL(top, left) {
console.log('fabricImageFromURL value', top, left);
fabric.Image.fromURL(URL, function (oImg) {
oImg.set('left', left).set('top', top);
oImg.hasControls = false;
oImg.hasBorders = false;
oImg.selectable = false;
canvas.add(oImg);
canvas.renderAll();
}, { "left": 0, "top": 0, "scaleX": 1, "scaleY": 1 });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.21/fabric.js"></script>
<canvas id="canvas"></canvas>
As we are not changing top value, no need to set top value all the time, just set left value for the image. pixelToSkip is the difference between mousemove pixel to call the function, if mouse move difference is less than that , then it wont call.
var URL = 'https://codyhouse.co/demo/360-degrees-product-viewer/img/alfa.png';
var canvas = new fabric.Canvas('canvas', {
selection: false
}),
imgObject;
var positions = {
topSteps: 1,
leftSteps: 16
};
var y = 0;
var x = 0;
var topStep;
var leftStep;
var isMouseDown = false;
var imgObject, pixelToSkip = 10;
var clickedPointer, currPointer, diff;
canWalk(URL, positions);
function canWalk(URL, positions) {
var myImage = new Image();
myImage.src = URL;
//var mDown = false;
//onloadevent
myImage.onload = function() {
topStep = myImage.naturalHeight / positions.topSteps;
leftStep = myImage.naturalWidth / positions.leftSteps;
canvas.setDimensions({
height : topStep,
width : leftStep
})
fabricImageFromURL(x, y);
};
}
//mouseevents
canvas.on('mouse:down', function(event) {
isMouseDown = true;
prevPointer = canvas.getPointer(event.e);
})
canvas.on('mouse:out', function(event) {
//console.log("mouseout")
/* x=0;
y=0;
fabricImageFromURL(x,y);*/
});
canvas.on('mouse:move', function(event) {
if (!isMouseDown) return;
currPointer = canvas.getPointer(event.e);
diff = currPointer.x - prevPointer.x;
if (diff < -pixelToSkip) {
if (x == positions.leftSteps) {
x = 0;
}
fabricImageFromURL(-x * leftStep)
x++;
prevPointer = currPointer;
} else if(diff > pixelToSkip){
if (x == 0) {
x = positions.leftSteps;
}
x--;
fabricImageFromURL(-x * leftStep)
prevPointer = currPointer;
}
});
canvas.on('mouse:up', function(event) {
isMouseDown = false;
})
function fabricImageFromURL(left) {
if (!imgObject) return
imgObject.set('left', left);
canvas.renderAll();
}
fabric.Image.fromURL(URL, function(oImg) {
imgObject = oImg;
oImg.set({
left: 0,
top: 0,
hasControls: false,
hasBorders: false,
selectable: false
});
canvas.add(oImg);
canvas.renderAll();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.21/fabric.js"></script>
<canvas id="canvas"></canvas>