Jump to content

Load canvas after ajax call


Go to solution Solved by Barand,

Recommended Posts

Page load I think calls the stuff like drawing canvas and the like, the problem here is that I don't know how to call the canvas to load after an ajax call. I can create the data I need, and see exactly what is expected, it's just the canvas isn't loading.

 

<edit>The canvas div is visible, it's just not drawing what is within.</edit>

 

 

Form

<form METHOD="POST" ACTION="">

	Project
	<select name="fm_project" onchange="showdata(this.form)" id="fm_project">
	<option value="2">Project A</option>
	<option value="1">Project B</option>
	<option value="3">Project C</option>
	<option value="0" SELECTED>Select One</option></select>

	Module
	<select name="fm_module" onchange="showdata(this.form)" id="fm_module">
	<option value="194">B</option>
	<option value="195">C</option>
	<option value="197">D</option>
	<option value="196">E</option>
	<option value="0" SELECTED>Select One</option></select>

	Stage
	<select name="fm_stage" onchange="showdata(this.form)" id="fm_stage">
	<option value="201">stagea</option>
	<option value="202">stageb</option>
	<option value="203">stage3</option>
	<option value="0" SELECTED>Select One</option></select>

	Part
	<select name="fm_part" onchange="showdata(this.form)" id="fm_part">
	<option value="1">Part1</option>
	<option value="2">Part2</option>
	<option value="3">part3</option>
	<option value="0" SELECTED>Select One</option></select>

</form>

<div id="graph_field">Start by choosing some filters above..</div>

JS

      <script>
        function showdata(form){
          var xhttp,
              project = form.fm_project.value,
              module = form.fm_module.value,
              stage = form.fm_stage.value,
              partno = form.fm_part.value;
              
          if (project == "") {
            document.getElementById("graph_field").innerHTML = "";
            return;
          }
          if (module == "") {
            document.getElementById("graph_field").innerHTML = "";
            return;
          }
          if (stage == "") {
            document.getElementById("graph_field").innerHTML = "";
            return;
          }
          if (partno == "") {
            document.getElementById("graph_field").innerHTML = "";
            return;
          }

          xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
              document.getElementById("graph_field").innerHTML = this.responseText;
            }
          };
          xhttp.open("GET", "printme.php?app=projects&ala=csajax&fm_project="+project+"&fm_module="+module+"&fm_stage="+stage+"&fm_part='"+partno+"'", true);
          xhttp.send();
        }
      </script>

canvas in the Ajax call refereed in the xhttp.open line above.

<canvas id="myCanvas" width="970" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
						

  do stuff...
						
						
</script>

Thanks!

Edited by KillGorack
Link to comment
https://forums.phpfreaks.com/topic/307141-load-canvas-after-ajax-call/
Share on other sites

I can foresee this being an issue when/if I get anything to draw in there to begin with. I'm not sure how to call a blanking of the canvas with an ajax call. Perhaps answering that question  will result in a way to also draw with t he ajax function.

  • Solution

In your printme.php, build the <canvas>...</canvas> element as a string then output the string.

 

I have never used canvas, but here is an example using SVG, which is fairly similar.

 

SAMPLE.HTML

 

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sample SVG with AJAX</title>
<style type='text/css'>
div {
    width: 40%;
    height: 150px;
    margin: 20px;
    padding: 20px;
    border: 1px solid gray;
    float: left;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type='text/javascript'>
    function draw()
    {
        var color = $("#colorselect").val();
        var sides = $("#sideselect").val();
        
        $.get (
            "sample_svg.php",
            { "color" : color ,
              "sides" : sides
            },
            function(resp) {
                $("#graphics").html(resp);
            }
        )
    }
    
    $().ready( function() {
        
        $("#colorselect").change( function() { draw(); })
        $("#sideselect").change( function() { draw(); })
    })
</script>
</head>
<body>
<div>
    Color: <select id='colorselect'>
               <option value='0'>- choose -</option>
               <option value='red'>Red</option>
               <option value='blue'>Blue</option>
               <option value='green'>Green</option>
            </select>
    <br><br>
    Sides: <select id='sideselect'>
               <option value='0'>- choose -</option>
               <option value='3'>Three</option>
               <option value='4'>Four</option>
               <option value='5'>Five</option>
               <option value='6'>Six</option>
               <option value='7'>Seven</option>
               <option value='8'>Eight</option>
            </select>
</div>  
<div id="graphics">
    <!-- graphic goes here -->
</div>  
</body>
</html>

 

SAMPLE_SVG.PHP (called via ajax)

 

<?php

$color = isset($_GET['color']) ? $_GET['color'] : '#888';
$sides = isset($_GET['sides']) ? $_GET['sides'] : 0;

exit( writeSVG($color, $sides) );            //output the SVG code

function writeSVG($color, $sides) {
    $svg = "<svg width='100' height='100' viewBox='0 0 100 100'>
        <rect x='0' y='0' width='100' height='100' fill='#CCC'/>\n";
    if ($sides < 3 || $sides >   {
        $svg .= "<circle cx='50' cy='50' r='50' stroke='black' fill='$color'/>\n";
    }
    else {
        $path = "M 100 50 ";
        $theta = 2 * M_PI / $sides;
        $svg .= "<circle cx='50' cy='50' r='50' stroke='black' fill='none'/>\n";
        for ($i=1; $i<$sides; $i++) {
            $x = 50 + 50 * cos($i * $theta);
            $y = 50 - 50 * sin($i * $theta);
            $path .= "L $x $y ";
        }
        $path .= "z ";
        $svg .= "<path d='$path' fill='$color' />\n";
    }    
    $svg .= "</svg>\n";
    return $svg;
}
?>
  • Like 1

I may be missing something here, but it looks like you're trying to draw in the canvas on the currently loaded page from the remote AJAX target script? It looks to me like all you're doing in the onreadystatechange() handler is updating the contents of the #graph_field div, which isn't a canvas element to begin with.

 

You'll need to apply the data returned from the AJAX call to the canvas on the currently loaded page. Whether that's - as Barand suggests - an html string that you replace the entire canvas contents with or a dataset you manipulate in JS to draw into the element, the modifications have to be made on the currently loaded page.

 

Basically, you're not loading the canvas element after the AJAX payload has been received (although you could, of course, dynamically create a new canvas element which you then append to the currently loaded page) you're manipulating the canvas element that's already there. That manipulation can happen at any time.

Further to maxxd's reply, here is an expansion of the above code.

The additional items (transparency and size) manipulate the elements of the current drawing directly, whereas the the first two, as before, cause a complete redraw of the image.

 

SAMPLE.HTML

 

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sample SVG with AJAX</title>
<style type='text/css'>
div {
    width: 40%;
    height: 150px;
    margin: 20px;
    padding: 20px;
    border: 1px solid gray;
    float: left;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type='text/javascript'>
    function draw()
    {
        var color = $("#colorselect").val();
        var sides = $("#sideselect").val();
        
        $.get (
            "sample_svg.php",
            { "color" : color ,
              "sides" : sides
            },
            function(resp) {
                $("#graphics").html(resp);
                $("#sizeselect").val('100');    // reset to default
                $("#transelect").val('1.0');    // reset to default
            }
        )
    }
    
    $().ready( function() {
        
        $("#colorselect").change( function() { draw(); })
        $("#sideselect").change( function() { draw(); })
        
        $("#sizeselect").change( function() {
            var sz = $(this).val();
            $("#drawing").attr({"width":sz, "height":sz});
        })
        
        $("#transelect").change( function() {
            var tr = $(this).val();
            $("#target").attr("fill-opacity", tr);
        })
    })
</script>
</head>
<body>
<div>
    Color: <select id='colorselect'>
               <option value='0'>- choose -</option>
               <option value='red'>Red</option>
               <option value='blue'>Blue</option>
               <option value='green'>Green</option>
            </select>
    <br><br>
    Sides: <select id='sideselect'>
               <option value='0'>- choose -</option>
               <option value='3'>Three</option>
               <option value='4'>Four</option>
               <option value='5'>Five</option>
               <option value='6'>Six</option>
               <option value='7'>Seven</option>
               <option value='8'>Eight</option>
            </select>
    <br><br>
    Transparency: <select id='transelect'>
            <option value='1.0'>None</option>
            <option value='0.5'>Medium</option>
            <option value='0.1'>High</option>
            </select>
    <br><br>
    Size: <select id='sizeselect'>
            <option value='100'>100 pixel</option>
            <option value='50'>50 pixel</option>
            <option value='150'>150 pixel</option>
            </select>
</div>  
<div id="graphics">
    <!-- graphic goes here -->
</div>  
</body>
</html>
 

 

SAMPLE_SVG.php

 

<?php

$color = isset($_GET['color']) ? $_GET['color'] : '#888';
$sides = isset($_GET['sides']) ? $_GET['sides'] : 0;

exit( writeSVG($color, $sides) );            //output the SVG code

function writeSVG($color, $sides) {
    $svg = "<svg id='drawing' width='100' height='100' viewBox='0 0 100 100'>
        <rect x='0' y='0' width='100' height='100' fill='#CCC'/>\n";
    if ($sides < 3 || $sides >   {
        $svg .= "<circle id='target' cx='50' cy='50' r='50' stroke='black' fill='$color'/>\n";
    }
    else {
        $path = "M 100 50 ";
        $theta = 2 * M_PI / $sides;
        $svg .= "<circle cx='50' cy='50' r='50' stroke='black' fill='none'/>\n";
        for ($i=1; $i<$sides; $i++) {
            $x = 50 + 50 * cos($i * $theta);
            $y = 50 - 50 * sin($i * $theta);
            $path .= "L $x $y ";
        }
        $path .= "z ";
        $svg .= "<path id='target' d='$path' fill='$color' />\n";
    }    
    $svg .= "</svg>\n";
    return $svg;
}
?>

 
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.