javascript - Casting for element access in Haxe for HTML-elements -




if want draw on canvas need 2d context of it. have canvas element in index.html of project:

 <body>     <canvas id="canv" width="200" height="200"></canvas>  </body> 

so need access element, ok, let's write code:

var cans:canvaselement = browser.document.getelementbyid("canv"); 

and in compile phase error:

src/main.hx:32: characters 2-78 : js.html.element should js.html.canvaselement

but if use unsafe casting, fine:

var cans:canvaselement = cast browser.document.getelementbyid("canv"); 

and works fine, access , can 2d context or make settings like:

cans.width = cans.height = 800; cans.style.backgroundcolor = 'rgba(158, 167, 184, 0.4)'; 

yes, know, "if works - don't fix", , understand normal, in principle need, when cast, can explain process me? mean - js.html.element should js.html.canvaselement? i'm started haxe learning (and programming in particular), i'm glad, can workable things, want know, why works when works , why not when doesn't.

js.html.element should js.html.canvaselement

this means compiler expected type canvaselement (because that's type hint cans variable tells it), encountered else (element in case). you're trying assign value returned getelementbyid() cans, getelementbyid() returns element.

since element less specific canvaselement (canvaselement extends element), can't assign element canvaselement - who's it's not divelement, or of other options? can decided when code executed / compiler can't know this, hence error (runtime vs compile time).

this works fine in case because know element id "canv" is in fact canvaselement, can silence compiler telling know you're doing cast. go wrong when returned value has type.





wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -