HTML Canvas Graphics

HTML Canvas Graphics <canvas> element का use करके web page पर graphics draw करने की technique है।
Canvas JavaScript के साथ काम करता है और pixel-based drawing area provide करता है।

Canvas real-time, dynamic और interactive graphics के लिए बहुत useful है।

canvas Element

<canvas> element web page पर drawing surface create करता है।

<canvas id="myCanvas" width="400" height="200"></canvas>

Canvas खुद कुछ draw नहीं करता, इसे control करने के लिए JavaScript जरूरी होती है।

Canvas Context

Canvas पर draw करने के लिए context लेना पड़ता है।
2D graphics के लिए getContext("2d") use किया जाता है।

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

Drawing a Rectangle

Canvas पर rectangle draw करने के लिए ये methods use होते हैं।

ctx.fillRect(20, 20, 150, 80);

Outline rectangle के लिए:

ctx.strokeRect(20, 20, 150, 80);

Clear करने के लिए:

ctx.clearRect(20, 20, 150, 80);

Drawing a Line

ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(200, 10);
ctx.stroke();

Drawing a Circle

Circle या arc draw करने के लिए arc() method use होता है।

ctx.beginPath();
ctx.arc(100, 60, 40, 0, 2 * Math.PI);
ctx.stroke();

Filling Shapes with Color

ctx.fillStyle = "blue";
ctx.fillRect(30, 30, 100, 50);

Stroke color set करने के लिए:

ctx.strokeStyle = "red";

Drawing Text on Canvas

Canvas पर text draw करने के दो तरीके होते हैं।

ctx.font = "20px Arial";
ctx.fillText("Hello Canvas", 50, 50);

Outline text के लिए:

ctx.strokeText("Hello Canvas", 50, 80);

Drawing Images on Canvas

Images canvas पर draw की जा सकती हैं।

var img = new Image();
img.src = "image.jpg";
img.onload = function() {
  ctx.drawImage(img, 10, 10, 150, 100);
};

Gradients in Canvas

Linear gradient example:

var grad = ctx.createLinearGradient(0, 0, 200, 0);
grad.addColorStop(0, "red");
grad.addColorStop(1, "yellow");
ctx.fillStyle = grad;
ctx.fillRect(20, 20, 200, 80);

Canvas Paths

Complex shapes बनाने के लिए paths use होते हैं।

ctx.beginPath();
ctx.moveTo(50, 20);
ctx.lineTo(150, 20);
ctx.lineTo(100, 80);
ctx.closePath();
ctx.stroke();

Canvas Animation Basics

Canvas में animation के लिए बार-बार redraw किया जाता है।

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
}
requestAnimationFrame(draw);

Canvas Use Cases

Games और game engines
Charts और graphs
Image editors
Custom animations

Canvas Limitations

Canvas content directly selectable नहीं होता
SEO और accessibility limited होती है
Large canvas redraw performance affect कर सकता है

HTML Canvas Graphics Summary

Canvas pixel-based drawing system है
JavaScript के बिना canvas useless है
Dynamic और real-time graphics के लिए best है
Games और animations में widely used है

Share your love