0% found this document useful (0 votes)
22 views21 pages

HTML5-SVG and Canvas Drawing Examples

Uploaded by

deepak chinagi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views21 pages

HTML5-SVG and Canvas Drawing Examples

Uploaded by

deepak chinagi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Write a program to create a Line and Rectangle using HTML5-SVG.

<!DOCTYPE html>
<html>
<head>
<title>SVG Line and Rectangle</title>
</head>
<body>
<svg width="400" height="400">
<!-- Create a line -->
<line x1="50" y1="50" x2="250" y2="50" stroke="black" stroke-
width="2" />
<!-- Create a rectangle -->
<rect x="50" y="100" width="200" height="100" fill="blue"
stroke="black" stroke-width="2" />
</svg>
</body>
</html>
Write a program to create a polygon, polyline HTML5-SVG.
<!DOCTYPE html>
<html>
<head>
<title>SVG Polygon and Polyline</title>
</head>
<body>
<svg width="400" height="400">
<!-- Create a polygon -->
<polygon points="100,50 200,10 300,50 350,200 250,200" fill="yellow"
stroke="black" strokewidth="2" />
<!-- Create a polyline -->
<polyline points="100,300 150,350 200,300 250,350 300,300"
fill="none" stroke="blue" strokewidth="2" />
</svg>
</body>
</html>
Write a program to create a star using HTML5-SVG.
<!DOCTYPE html>
<html>
<head>
<title>SVG Star</title>
</head>
<body>
<svg width="400" height="400">
<polygon points="200,50 237.5,162.5 362.5,162.5 262.5,237.5 300,350
200,275 100,350 137.5,237.5
37.5,162.5 162.5,162.5"
fill="yellow" stroke="black" stroke-width="2" />
</svg>
</body>
</html>
Write a program to create a Line and Rectangle using HTML5-CANVAS.
<!DOCTYPE html>
<html>
<head>
<title>Canvas Line and Rectangle</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<script>
// Get the canvas element
var canvas = [Link]("myCanvas");
var ctx = [Link]("2d");
// Draw a line
[Link]();
[Link](50, 50); // Starting point of the line
[Link](200, 50); // Ending point of the line
[Link] = 2; // Set the line width
[Link] = "blue"; // Set the line color
[Link]();
// Draw a rectangle
[Link]();
[Link](50, 100, 200, 100); // x, y, width, height
[Link] = 2; // Set the line width
[Link] = "red"; // Set the line color
[Link] = "yellow"; // Set the fill color
[Link]();
[Link]();
</script>
</body>
</html>
Write a program to create Bezier Curves using HTML5-CANVAS.
<!DOCTYPE html>
<html>
<head>
<title>Canvas Bezier Curves</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<script>
// Get the canvas element
var canvas = [Link]("myCanvas");
var ctx = [Link]("2d");
// Quadratic Bezier Curve
[Link]();
[Link](50, 200); // Starting point
[Link](200, 50, 350, 200); // Control point, Ending point
[Link] = 2; // Set the line width
[Link] = "blue"; // Set the line color
[Link]();
// Cubic Bezier Curve
[Link]();
[Link](50, 300); // Starting point
[Link](150, 200, 250, 400, 350, 300); // Control point 1,
Control point 2, Ending point
[Link] = 2; // Set the line width
[Link] = "red"; // Set the line color
[Link]();
</script>
</body>
</html>
Write a program to create Draw Linear Gradient using HTML5-
CANVAS.
<!DOCTYPE html>
<html>
<head>
<title>Canvas Linear Gradient</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<script>
// Get the canvas element
var canvas = [Link]("myCanvas");
var ctx = [Link]("2d");
// Create a linear gradient
var gradient = [Link](0, 0, 400, 0); // (x0, y0, x1, y1)
// Define gradient colors
[Link](0, "red");
[Link](0.5, "green");
[Link](1, "blue");
// Fill a rectangle with the gradient
[Link] = gradient;
[Link](50, 50, 300, 200);
</script>
</body>
</html>
Write a program to rectangle translation using HTML5-CANVAS.
<!DOCTYPE html>
<html>
<head>
<title>Canvas Rectangle Translation</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<script>
// Get the canvas element
var canvas = [Link]("myCanvas");
var ctx = [Link]("2d");
// Initial position and size of the rectangle
var x = 50;
var y = 50;
var width = 100;
var height = 50;
// Function to draw the rectangle at the current position
function drawRectangle() {
[Link](0, 0, [Link], [Link]); // Clear the canvas
[Link] = "blue"; // Set the fill color
[Link](x, y, width, height); // Draw the rectangle
}
// Function to handle the translation of the rectangle
function translateRectangle(dx, dy) {
x += dx; // Update the x position
y += dy; // Update the y position
drawRectangle(); // Redraw the rectangle at the new position
}
// Initial drawing of the rectangle
drawRectangle();
// Move the rectangle using arrow keys
[Link]("keydown", function (event) {
var step = 10; // Step size for translation
switch ([Link]) {
case 37: // Left arrow key
translateRectangle(-step, 0);
break;
case 38: // Up arrow key
translateRectangle(0, -step);
break;
case 39: // Right arrow key
translateRectangle(step, 0);
break;
case 40: // Down arrow key
translateRectangle(0, step);
break;
}
});
</script>
</body>
</html>
Write a program to rectangle rotation using HTML5-CANVAS.
<!DOCTYPE html>
<html>
<head>
<title>Canvas Rectangle Rotation</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<script>
// Get the canvas element
var canvas = [Link]("myCanvas");
var ctx = [Link]("2d");
// Initial position and size of the rectangle
var x = 150;
var y = 150;
var width = 100;
var height = 50;
var angle = 0; // Initial rotation angle
// Function to draw the rotated rectangle
function drawRotatedRectangle() {
[Link](0, 0, [Link], [Link]); // Clear the canvas
// Translate to the center of the rectangle
[Link](x + width / 2, y + height / 2);
// Rotate the canvas
[Link](([Link] / 180) * angle);
// Draw the rectangle
[Link] = "blue"; // Set the fill color
[Link](-width / 2, -height / 2, width, height);
// Reset the transformations
[Link](-([Link] / 180) * angle);
[Link](-(x + width / 2), -(y + height / 2));
}
// Function to handle the rotation of the rectangle
function rotateRectangle(dAngle) {
angle += dAngle; // Update the rotation angle
drawRotatedRectangle(); // Redraw the rotated rectangle
}
// Initial drawing of the rotated rectangle
drawRotatedRectangle();
// Rotate the rectangle using arrow keys
[Link]("keydown", function (event) {
var rotationAngle = 10; // Angle of rotation in degrees
switch ([Link]) {
case 37: // Left arrow key
rotateRectangle(-rotationAngle);
break;
case 39: // Right arrow key
rotateRectangle(rotationAngle);
break;
}
});
</script>
</body>
</html>
Write a program to rectangle scaling using canvas.
<!DOCTYPE html>
<html>
<head>
<title>Canvas Rectangle Scaling</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<script>
// Get the canvas element
var canvas = [Link]("myCanvas");
var ctx = [Link]("2d");
// Initial position and size of the rectangle
var x = 100;
var y = 100;
var width = 100;
var height = 50;
// Function to draw the rectangle
function drawRectangle() {
[Link](0, 0, [Link], [Link]); // Clear the canvas
[Link] = "blue"; // Set the fill color
[Link](x, y, width, height); // Draw the rectangle
}
// Function to handle the scaling of the rectangle
function scaleRectangle(scaleFactor) {
width *= scaleFactor; // Update the width
height *= scaleFactor; // Update the height
drawRectangle(); // Redraw the rectangle with the new size
}
// Initial drawing of the rectangle
drawRectangle();
// Scale the rectangle using arrow keys
[Link]("keydown", function (event) {
var scaleStep = 0.1; // Step size for scaling
switch ([Link]) {
case 37: // Left arrow key
scaleRectangle(1 - scaleStep); // Shrink width
break;
case 38: // Up arrow key
scaleRectangle(1 + scaleStep); // Enlarge height
break;
case 39: // Right arrow key
scaleRectangle(1 + scaleStep); // Enlarge width
break;
case 40: // Down arrow key
scaleRectangle(1 - scaleStep); // Shrink height
break;
}
});
</script>
</body>
</html>
Write a program to rotate a small image repeatedly using HTML5-
CANVAS Animation.
<!DOCTYPE html>
<html>
<head>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
// Get the canvas element and its 2D context
var canvas = [Link]("myCanvas");
var ctx = [Link]("2d");
// Load the image
var image = new Image();
[Link] = "path/to/your/[Link]";
[Link] = function() {
// Start the animation once the image is loaded
requestAnimationFrame(animate);
};
var angle = 0; // Initial rotation angle
function animate() {
// Clear the canvas
[Link](0, 0, [Link], [Link]);
// Save the current state of the canvas
[Link]();
// Translate to the center of the canvas
[Link]([Link] / 2, [Link] / 2);
// Rotate the canvas by the current angle
[Link](([Link] / 180) * angle);
// Draw the image at its center
[Link](
image,
-[Link] / 2,
-[Link] / 2,
[Link],
[Link]
);
// Restore the canvas state
[Link]();
// Update the angle for the next frame
angle += 1;
// Request the next animation frame
requestAnimationFrame(animate);
}
</script>
</body>
</html>

Common questions

Powered by AI

HTML5 Canvas facilitates interactivity in web applications through event handling and real-time graphical updates. For translation, keydown events are captured to move objects, like translating a rectangle by adjusting its coordinates incrementally . Rotation interactivity is likewise implemented by altering rotation angles upon receiving user inputs, such as arrow key presses. This interaction creates dynamic visuals where objects respond to user commands seamlessly . Besides improving user engagement, this approach leverages CSS-like ease of handling events with JavaScript's granularity in controlling each draw operation, offering unmatched flexibility in rendering adaptive interfaces.

Scaling a rectangle in HTML5 Canvas involves programmatically adjusting its width and height properties, often through a scale factor. The process requires clearing the canvas and redrawing the rectangle with updated dimensions . User interaction significantly influences scaling through event listeners that modify dimensions interactively based on user inputs, such as arrow keys that proportionally change the rectangle’s size. Key considerations include maintaining the rectangle’s aspect ratio, avoiding excessive distortion, and handling potential edge overflow within the canvas boundaries . Effective feedback loops are supported by immediate redraws following size adjustments.

HTML5 Canvas offers significant benefits for game development through efficient pixel-by-pixel control and direct rendering to the browser, enabling high-performance graphics suitable for complex scenes and moving elements. Animation handling is effective due to the ability to use the requestAnimationFrame method, which optimizes frame redraws by synchronizing updates with the display refresh rate . This minimizes CPU usage and power consumption, crucial for maintaining smooth, fluid animations. Additionally, Canvas supports extensive API flexibility for creating custom effects and real-time graphical updates, elements critical in developing engaging, interactive games.

In HTML5 Canvas, rectangle translation is achieved by adjusting the rectangle's position coordinates and redrawing it. The implementation uses JavaScript functions to modify the x and y coordinates of the rectangle based on input events. Event handling plays a crucial role as it captures specific key presses (e.g., arrow keys for directional movement) and triggers translation functions. Specifically, an event listener detects keydown events and switches on key codes to determine movement direction, updating the rectangle's position and invoking a redraw function .

SVG retains advantages in application contexts that require resolution independence, accessibility, and direct manipulation of DOM elements. Since SVG is vector-based, it scales perfectly across diverse screen sizes without quality degradation, making it ideal for responsive design and printing. SVG graphics are inherent XML nodes in the DOM, allowing CSS styling and JavaScript interaction straightforwardly, which benefits scenarios where manipulation and accessibility are essential . Conversely, Canvas excels in performance-intensive, pixel-manipulated scenes, such as games or animations, where rapid changes outweigh the hierarchical manipulations SVG facilitates.

Rotating an image in HTML5 Canvas animation involves several stages. Initially, the image is loaded and upon completion, the animation function is invoked. This function clears the canvas, saves the current state, and translates the context to the canvas center to ensure the image rotates around its center . The rotation is performed using the rotate method, where the angle is incremented for successive frames. After drawing the image with drawImage, the canvas state is restored to cancel transformations, preparing it for the next frame's fresh transformations . Saving and restoring are crucial for maintaining consistent canvas state across frames, avoiding cumulative transformations that would otherwise skew the image.

HTML5 SVG and Canvas differ in their rendering approaches and use cases. SVG (Scalable Vector Graphics) defines shapes as XML-based vectors, allowing for easy manipulation, scalability without loss of quality, and interaction with CSS and JavaScript. For example, a line in SVG is defined using the <line> element with attributes for coordinates and styles . Conversely, Canvas is a bitmap-based rendering model where graphics are drawn via JavaScript commands. For instance, to draw a line on Canvas, JavaScript context methods like beginPath() and moveTo() are employed . This pixel-based approach suits dynamic graphics and faster rendering changes but lacks the resolution independence of SVG.

Creating a linear gradient on an HTML5 Canvas involves several steps. First, a gradient object is created using the context's createLinearGradient method, specifying the start and end coordinates (x0, y0, x1, y1). Next, color stops are added using addColorStop with positional values and corresponding colors. This gradient is then assigned to the fillStyle property of the context. Finally, a shape (e.g., rectangle) is filled using the gradient with fillRect . This technique enhances visualization by allowing smooth color transitions and enriching the graphical interface with depth and artistic appeal.

The 'translate' method in HTML5 Canvas is employed to move the origin of the canvas to a new location, facilitating easier positioning of subsequent drawings. This transformation updates the coordinate system, allowing shapes or images to be drawn relative to the new origin without manually calculating new positioning for each object . In graphic transformations, translating the origin simplifies complex transformations like rotations or scaling, centering them around the desired axis. It is especially useful before applying further transformations, such as rotation, to maintain desired alignment and prevent objects from appearing outside the intended view area.

To simulate complex shapes like stars in HTML5 Canvas, one must define the vertex coordinates mathematically or use pre-calculated values. This involves using the context's beginPath, moveTo, and lineTo methods to connect points sequentially . Challenges include precise coordinate calculation, ensuring symmetrical aesthetics, and handling overlapping lines, which could result in unexpected visual artifacts. Moreover, rendering performance might suffer if shapes are dynamic and recalculated frequently. Therefore, careful planning of vertex logic and optimization for drawing methods is essential to manage computational load and maintain visual fidelity.

You might also like