(Combining Drawing Shape, Line, and Text on Canvas)
Elements HTML5 <canvas> is used to draw graphics, on the fly, via scripting (usually JavaScript).
The <canvas> is only a container for graphics. You must use a script to actually draw the graphics.
Canvas has several methods for drawing lines, boxes, circles, characters and adding images.
Support browser
Google Chrome, Firefox, Internet Explorer, Opera, Safari
Chrome, Firefox, Internet Explorer 9+, Opera and Safari support for the <canvas>.
Note: Internet Explorer 8 is the latest version, not support for <canvas> element.
Make Canvas
Canvas is the square are made using the tag <canvas>, by default canvas is not particularly border and fill it.
example :
<canvas id="myCanvas" width="200" height="100" >
Note: Always specify the id attribute (which will be called in the script), and the width and height attributes to specify the size of the canvas.
Tips: You can have multiple elements <canvas> on the HTML page.
To add a border, use the style attribute:
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
Canvas is defined using the <canvas>, which must have a length and width. In addition, to ensure that the browser will display correctly, then the HTML5 doctype must also be included. As a first step, create a .html file with the following contents.
For example, that I made good use.
To do an output, then click
<li><a href="javascript:square()">Square</a></li>
<li><a href="javascript:line()">Line</a></li>
<li><a href="javascript:circle()">Circle</a></li>
<li><a href="javascript:text()">Text</a></li>
The output is
<body >
<p><b>JavaScript Canvas</b></p>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>
<li><a href="javascript:square()">Square</a></li>
<li><a href="javascript:line()">Line</a></li>
<li><a href="javascript:circle()">Circle</a></li>
<li><a href="javascript:text()">Text</a></li>
</body>
function square(){
var cv1 = document.getElementById('myCanvas');
var ctx = cv1.getContext('2d');
ctx.fillStyle="#000000";
ctx.fillRect(10,10,90,40);
console.log(ctx);
}
To draw a line, you can use the method moveTo (x, y) to determine the starting point of the depiction, followed by lineTo (x, y) to draw a route. Need both those methods are still not displaying the actual line, but only sketch only. To add a line, the method needs to be called stroke (). Here's an example of drawing a grid on the canvas.
function line(){
var cv1 = document.getElementById('myCanvas');
var ctx = cv1.getContext('2d');
ctx.moveTo(100,50);
ctx.lineTo(200,100);
ctx.stroke();
}
function circle(){
var cv1 = document.getElementById('myCanvas');
var ctx = cv1.getContext('2d');
ctx.beginPath();
ctx.arc(100,50,40,0,2*Math.PI);
ctx.stroke();
}
function text(){
var cv1 = document.getElementById('myCanvas');
var ctx = cv1.getContext('2d');
ctx.font='20px, arial';
ctx.fillStyle="#ffffff";
ctx.fillText('square',20,20);
ctx.strokeText('circle',50,70);
}
↲











