简体   繁体   中英

Why drawing line on canvas doesn't appear?

I'm using a html 5 to draw a line on canvas with a button.

Does anybody know why?

<!DOCTYPE html>
<html>

 <body onload="">

<canvas id="myCanvas" width="400" height="200" style="border:1px solid #000000;">
  Your browser does not support the HTML5 canvas tag.
</canvas>
<button name="draw" onclick="drawLine()">Draw Line</button>
<script type="text/javascript" src="canvashtml5.js" ></script>

</body>
</html>

darwLine function is on the external javascript as canvasHtml5.js:

function drawLine(){
   var canvas = document.getElementById(myCanvas);
   var context = canvas.getContext("2d");
   context.moveTo(0,0);
   context.lineTo(300,150);
   context.stroke();
}
myCanvas
{
   var c=document.getElementById("myCanvas");
   var ctx=c.getContext("2d");
   ctx.fillStyle="#FFFF00";
   ctx.fillRect(0,0,150,75);
}

I forgot to put myCanvas to quot like this: "myCanvas".

this var canvas = document.getElementById(myCanvas); must be like var canvas = document.getElementById("myCanvas");

Alternative:

Add an event listener to your button like so:

document.getElementById('drawLineBtn').addEventListener('click', drawLine, false);

This will cut down on your work in the future. See http://jsfiddle.net/kbXAN/23/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM