Other HTML Canvas Graphics

In our previous post we have learnt about HTML Canvas and create some canvas drawings with the help of JavaScript. Now in this post we will about some other HTML canvas graphics.
Draw Linear Gradient
In an example below we will write a code to draw a linear gradient:
Example
<!DOCTYPE html> <html> <head> <title> Draw Linear Gradient </title> <body> <canvas id = "myCanvas" width="200" height = "100" style= "border:1px solid #d3d3d3;"> <script> var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); // Create gradient var grd = ctx.createLinearGradient(0, 0, 200, 0); grd.addColorStop(0, "black"); grd.addColorStop(1, "white"); // Fill with gradient ctx.fillStyle = grd; ctx.fillRect(10, 10, 150, 80); </script> </body> </html>
Draw a Circular Gradient
Example
<!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML canvas tag.</canvas> <script> var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); // Create gradient var grd = ctx.createRadialGradient(75,50,5,90,60,100); grd.addColorStop(0,"black"); grd.addColorStop(1,"white"); // Fill with gradient ctx.fillStyle = grd; ctx.fillRect(10,10,150,80); </script> </body> </html>
Output
Draw a Stroke Text
Example
<!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="300" height="100" style="border:2px solid #d3d3d3;"> Your browser does not support the HTML canvas tag.</canvas> <script> var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.font = "30px Arial"; ctx.strokeText("This is a stroke text", 10,50); </script> </body> </html>
Output
Draw an Arc
Example
<!DOCTYPE html> <html> <head> <title>Drawing an Arc</title> <style> canvas { border: 2px solid #d3d3d3; } </style> <script> window.onload = function() { var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); context.arc(150, 150, 80, 1.2 * Math.PI, 1.8 * Math.PI, false); context.stroke(); }; </script> </head> <body> <canvas id="myCanvas" width="300" height="200"></canvas> </body> </html>
Output
How to Fill Colors Inside the Canvas Shapes
We can fill colors inside the canvas shapes by using the fillStyle() method.
In a below example we will show you how to fill a black color rectangular shaped inside the canvas.
Example
<!DOCTYPE html> <html> <head> <title>Filling Color inside the Canvas</title> <style> canvas { border: 2px solid #d3d3d3; } </style> <script> window.onload = function() { var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); context.rect(50, 50, 200, 100); context.fillStyle = "#000000"; context.fill(); context.lineWidth = 5; context.strokeStyle = "white"; context.stroke(); }; </script> </head> <body> <canvas id="myCanvas" width="300" height="200"></canvas> </body> </html>
Output
Related Posts
Other HTML Canvas Graphics – crus4
3 thoughts on “Other HTML Canvas Graphics – crus4”