Skip to main content
Inspiring
June 16, 2020
質問

Movieclip in canvas throws error when I try to target it.

  • June 16, 2020
  • 返信数 1.
  • 484 ビュー

I have a movieclip that I made on the timeline (a blue square) which I have given the instance name of "blueSquare".

 

The following code works:

this.blueSquare.x = 800;

 

But when I try to put that in a function, it throws an error saying blueSquare is undefined:

function moveMe() {
	this.blueSquare.x = 800;
}
moveMe();

This also is undefined:

function moveMe() {
	blueSquare.x = 800;
}
moveMe();

I've tried calling my square 'stage.blueSquare', 'stage.canvas.blueSquare', and others.

 

Any idea why this doesn't work? 

 

このトピックへの返信は締め切られました。

返信数 1

kglad
Community Expert
Community Expert
June 17, 2020

because "this" is undefined in moveMe.

 

use:

 

moveMe.bind(this)();

 

if you want "this" to be defined in moveMe.

Inspiring
June 17, 2020

Thank you for the help!

 

Perhaps you can help me with my resize issue. I want to be able to move a movieclip around when the window is resized. I have this:

function resizeMe(evt) {
	blueSquare.x = 800; //throws error because blueSquare is undefined
	this.blueSquare.x = 800; //throws error because blueSquare is undefined
}
window.addEventListener("resize", resizeMe);

I think I have scope issues, but I don't know how to fix them. If I create an element with code and do stage.addChild(element) I can target that element fine. However, elements that are already on the stage in the IDE (like my blueSquare) cannot be targeted. They are undefined. Do you know why that is?

kglad
Community Expert
Community Expert
June 17, 2020

and for others this is the preferred solution:

 

function resizeMe(evt) {
	//blueSquare.x = 800; //throws error because blueSquare is undefined
	this.blueSquare.x = 800; //throws error because blueSquare is undefined
}
window.addEventListener("resize", resizeMe.bind(this));