Jump to content
Reizvoller

Canvas and Scripting

Recommended Posts

Reizvoller

Greetings!

I am having an issue that I can't seem to be able to figure out. I would really appreciate an extra pair of eyes to validate my work so far.

All this is, so far, is just a bunch of shapes on an HTML page. It is to be a very simple game ( just exploring Javascript through making this ) but right now I am just building the framework/elements.

The script is this 

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
      #canvas-container {
   width: 100%;
   text-align:center;
}

canvas {
   display: inline;
}
    </style>
    

  </head>
  <body onload="startUp()">

  <div id="canvas-container">
    <canvas id="game" width="300" height="500"></canvas>
  </div>
 
<script>
    
    var canvas = document.getElementById('game');
    var ctx = canvas.getContext('2d');
    
    var x = canvas.width;
    var y = canvas.height;
    var scoreVal = 0;
    var itemXRand = Math.floor(Math.random() * x) + 1
    
    ctx.stroke();
    
    function cloud(){
    
    ctx.beginPath();
      ctx.moveTo(170, 30);
      ctx.bezierCurveTo(130, 100, 130, 150, 230, 150);
      ctx.bezierCurveTo(250, 180, 320, 180, 340, 150);
      ctx.bezierCurveTo(420, 150, 420, 120, 390, 100);
      ctx.bezierCurveTo(430, 40, 370, 30, 340, 50);
      ctx.bezierCurveTo(320, 5, 250, 20, 250, 50);
      ctx.bezierCurveTo(200, 5, 150, 20, 170, 80);
      ctx.closePath();
      ctx.lineWidth = 5;
      ctx.fillStyle = '#8ED6FF';
      ctx.fill();
      ctx.strokeStyle = '#0000ff';
      ctx.stroke();
    
    }

    function workArea(){
      ctx.beginPath();
      ctx.rect(0, 0, x, y);
      ctx.fillStyle = "#2ab9ff";
      ctx.fill();
      ctx.stroke = 1;
}

    function topRect(){
      ctx.beginPath();
      ctx.rect(0, 0, x, 30);
      ctx.fillStyle = "#D3D3D3";
      ctx.fill();
      ctx.stroke = 1;
}

    function scoreKeep(){   
    ctx.font = "15px Arial";
    ctx.fillStyle = "#000000";
    ctx.fillText("Score "+scoreVal,5, 25);  
    }

    function bttmRect(){
      ctx.beginPath();
      ctx.rect(0, y-30, x, 30);
      ctx.fillStyle = '#5bc928';
      ctx.fill();
      ctx.stroke = 1;
}


    function monstRect(){
      ctx.beginPath();
      ctx.rect(0, y-80, x, 30);
      ctx.fillStyle = 'red';
      ctx.fill();
      ctx.stroke = 1;
}

    function itemCirc(){
    var centerX = itemXRand
    var radius = 15;
    var positionY = 45;
    
      ctx.beginPath();
      ctx.arc(centerX, positionY, radius, 0, 2 * Math.PI, false);
      ctx.fillStyle = randomColor();
      ctx.fill();
      ctx.lineWidth = 1;
      ctx.strokeStyle = '#003300';
      ctx.stroke();
}

    function startUp(){
    workArea();
    topRect();
    bttmRect();
    scoreKeep();
    itemCirc();
    monstRect();
    cloud();
    }
    
    function randomColor(){ 
        return('#'+Math.floor(Math.random()*16777215).toString(16));
}
    
</script>

  </body>
</html>

The issue is that cloud() and monstRect() will not show up when the page loads. If I comment out workArea(), topRect(), and bttmRect() in the function "startUp()" then monstRect() and cloud() show up. I've re-read those little snippets of code for those three areas that I comment out and I can't see where I have gone wrong.

Any advice or if you can spot my mistake I would really appreciate it.

Thank you!

-Reiz

Share this post


Link to post
Share on other sites
guinness
  1. Bad use of ASI (automatic semi-colon insertion)
  2. Polluting the global scope (use an IIFE or ES2015 module)
  3. I am not really seeing your issue, though I do see errors when I move your code to http://jsbin.com/wededadera/edit?html,js,console,output. Check the console and you will see what I mean.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Share this post


Link to post
Share on other sites
Reizvoller

Greetings!

Your reply is amazingly helpful and friendly.

I actually ended up scrapping the entire thing and went to work in Python for fun :)

I will review my old ( this one ) code and apply the information you provided.

Thank you for your time and assistance!

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • guinness
      By guinness
      Just trying out the latest version of AutoIt and thinking more functional
      #include <Array.au3> ; Example ; An example of filtering an array and reducing an array, using a function reference. ; This is similiar to how it would be done in the likes of JavaScript i.e. more functional (declarative) Local $aArray[] = [1, 2, 3, 50, 30, 40, 20, 30] Local $aFiltered = _ArrayFilter($aArray, GtrThan30) _ArrayDisplay($aFiltered, '_ArrayFilter::') Local $iSum = _ArrayReduce($aArray, SumValues) ConsoleWrite('_ArrayReduce::' & $iSum & @CRLF) Func SumValues($a, $b) Return $a + $b EndFunc ;==>SumValues Func GtrThan30($vValue) Return $vValue > 30 EndFunc ;==>GtrThan30 Func _ArrayFilter($aArray, $fFunc) If Not IsArray($aArray) Then ; Null is more appropriate than returning the likes of -1 or an empty array Return SetError(1, 0, Null) EndIf If Not IsFunc($fFunc) Then ; Null is more appropriate than returning the likes of -1 or an empty array Return SetError(2, 0, Null) EndIf Local Const $iLen = UBound($aArray) - 1 Local $aFiltered[$iLen] Local $iIndex = 0 For $i = 0 To $iLen Local $bIsFiltered = __ArrayCall($fFunc, $aArray[$i], $i) If @error Then Return SetError(@error, @extended, Null) ElseIf $bIsFiltered Then $aFiltered[$iIndex] = $aArray[$i] $iIndex += 1 EndIf Next ReDim $aFiltered[$iIndex] Return $aFiltered EndFunc ;==>_ArrayFilter Func _ArrayReduce($aArray, $fFunc, $vInitial = Default) If Not IsArray($aArray) Then ; Null is more appropriate than returning the likes of -1 or an empty array Return SetError(1, 0, Null) EndIf If Not IsFunc($fFunc) Then ; Null is more appropriate than returning the likes of -1 or an empty array Return SetError(2, 0, Null) EndIf Local $bHasInitial = @NumParams >= 3 For $i = 0 To UBound($aArray) - 1 If $bHasInitial Then $vInitial = __ArrayCall($fFunc, $vInitial, $aArray[$i], $i) If @error Then Return SetError(@error, @extended, Null) EndIf Else $bHasInitial = True $vInitial = $aArray[$i] EndIf Next Return $vInitial EndFunc ;==>_ArrayReduce Func __ArrayCall($fFunc, $vArg1 = Default, $vArg2 = Default, $vArg3 = Default) Local $vRetValue = Call($fFunc, $vArg1) If @error = 0xDEAD And @extended = 0xBEEF Then $vRetValue = Call($fFunc, $vArg1, $vArg2) If @error = 0xDEAD And @extended = 0xBEEF Then $vRetValue = Call($fFunc, $vArg1, $vArg2, $vArg3) If @error = 0xDEAD And @extended = 0xBEEF Then ; The function exists, but there is no appropriate function signature Return SetError(3, 0, Null) EndIf EndIf EndIf Return SetError(@error, @extended, $vRetValue) EndFunc ;==>__ArrayCall  
    • Dent
      By Dent
      As the title says. I open IE11 and navigate to a page with the following HTML5 file upload container in Capture0.JPG
      I want to click Add Files but I haven't been able to. Here's the code that handles the Add Files button in Capture.JPG
      _IEGetObjectById and then using _IEAction to click it doesn't work. I can't give access to the actual page unfortunately because it's password protected.
      All suggestions welcome.


    • Chimp
      By Chimp
      An example on how to inject jQuery into a web page
      It can be useful to manage the page from AutoIt using jQuery.
      Idea from here: http://www.learningjquery.com/2009/04/better-stronger-safer-jquerify-bookmarklet
      Suggestions and improvements are welcome
      #include <ie.au3> Example() Func Example() Local $oIE = _IECreate("www.google.com") Local $jQuery = _jQuerify($oIE) MsgBox(0, "Version", "jQuery version: " & $jQuery.fn.jquery) MsgBox(0, "Example", "click ok to exit." & @CRLF & "Google logo will fade out by jQuery...") $jQuery('#hplogo').fadeOut(3000) ; jQuery will fade out the google logo EndFunc ;==>Example ; #FUNCTION# ==================================================================================================================== ; Name ..........: _jQuerify ; Description ...: ; Syntax ........: _jQuerify(Byref $oIE) ; Parameters ....: $oIE - Object variable of an InternetExplorer.Application. ; Return values .: an object variable pointing to the jQuery library ; Author ........: Chimp ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........: ; Example .......: ; =============================================================================================================================== Func _jQuerify(ByRef $oIE) Local $jsEval, $jQuery, $otherlib = False ; create a reference to the javascript eval() function $oIE.document.parentWindow.setTimeout('document.head.eval = eval', 0) Do Sleep(250) $jsEval = Execute('$oIE.Document.head.eval') Until IsObj($jsEval) ; if jQuery is not already loaded then load it If $jsEval("typeof jQuery=='undefined'") Then ; check if the '$' (dollar) name is already in use by other library If $jsEval("typeof $=='function'") Then $otherlib = True Local $oScript = $oIE.document.createElement('script'); $oScript.type = 'text/javascript' ; If you want to load jQuery from a disk file use the following statement ; where i.e. jquery-1.9.1.js is the file containing the jQuery source ; (or also use a string variable containing the whole jQuery listing) ;~ $oScript.TextContent = FileRead(@ScriptDir & "\jquery-1.9.1.js") ; <--- from a file ; If you want to download jQuery from the web use this statement $oScript.src = 'https://code.jquery.com/jquery-latest.min.js' ; <--- from an url $oIE.document.getElementsByTagName('head').item(0).appendChild($oScript) Do Sleep(250) Until $jsEval("typeof jQuery == 'function'") EndIf Do Sleep(250) $jQuery = $jsEval("jQuery") Until IsObj($jQuery) If $otherlib Then $jsEval('jQuery.noConflict();') Return $jQuery EndFunc ;==>_jQuerify  
    • XaelloNegative
      By XaelloNegative
      Hi there.
      Im having some kind of a coder block here, 
      <td class="treeview ctl00_CenterContent_objTreeView_2" style="white-space:nowrap;"> <input type="checkbox" name="ctl00_CenterContent_objTreeViewn1CheckBox" id="ctl00_CenterContent_objTreeViewn1CheckBox"> <span class="ctl00_CenterContent_objTreeView_0 treeview ctl00_CenterContent_objTreeView_1" id="ctl00_CenterContent_objTreeViewt1" style="border-style:none;font-size:1em;"> <i class="fa fa-file-code-o fa-fw"> </i> <span data-placement="bottom" data-toggle="tooltip" title="" data-original-title="Tool tip for said part">REFUNDS</span></span></td> this is a code directly from the website im working with. I was thinking of inserting a javascript that would get the "REFUNDS" part. Any ideas on how to do so?
      Any thoughts will be highly appreciated.
    • TheAutomator
      By TheAutomator
      Hi!

      I'm trying to script an ellipse drawing algorithm in AutoIT for learning purposes.
      I use an edit control to "draw" the ellipse with characters.
      The code i have works kinda good but i would like to see if others around here know a better algorithm to do it..
      I would like to be able to give the x, y and width, height arguments to the function and not have to start at the middle point and draw the ellipse around it.

      side note, the ellipse glitches when it has to be 2 pixels high too..
       
      func ellipsePlotPoints ($xc,$yc, $x,$y) pixel ($xc + $x, $yc + $y) pixel ($xc - $x, $yc + $y) pixel ($xc + $x, $yc - $y) pixel ($xc - $x, $yc - $y) endfunc func ellipse($xc,$yc, $a,$b) local $a2 = $a * $a local $b2 = $b * $b local $twoa2 = 2 * $a2 local $twob2 = 2 * $b2 local $p local $x = 0 local $y = $b local $px = 0 local $py = $twoa2 * $y ; Plot the initial point in each quadrant. ellipsePlotPoints ($xc,$yc, $x,$y) ; Region 1 $p = int($b2 - ($a2 * $b) + (0.25 * $a2)) while ($px < $py) $x+=1 $px += $twob2 if ($p < 0) then $p += $b2 + $px else $y-=1 $py -= $twoa2 $p += $b2 + $px - $py endif ellipsePlotPoints ($xc,$yc, $x,$y) wend ; Region 2 $p = int ($b2 * ($x+0.5) * ($x+0.5) + $a2 * ($y-1) * ($y-1) - $a2 * $b2) while ($y > 0) $y-=1 $py -= $twoa2 if ($p > 0) then $p += $a2 - $py else $x+=1 $px += $twob2 $p += $a2 - $py + $px endif ellipsePlotPoints ($xc,$yc, $x,$y) wend endfunc  
×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.