Sunday, October 15, 2023

Draw X Code

<button onclick="drawX()">Draw X</button> <!-- Button to call the 'drawX' function when clicked -->
<button onclick="eraseAll()">Erase all</button> <!-- Button to call the 'eraseAll' function when clicked -->
<canvas height="400" id="field1" width="500"></canvas> <!-- HTML5 canvas element with a specific width and height, given the id 'field1' -->
<script>
// Function to draw X
function drawX(){
const sketch1 = document.querySelector('#field1'); // Get the canvas element with the id 'field1'
if (!sketch1.getContext) { return; } // Check if the canvas is supported in the browser
const ctx = sketch1.getContext('2d'); // Get the 2D drawing context of the canvas
// Set line stroke and line width
ctx.strokeStyle = 'red'; // Set the line color to red
ctx.lineWidth = 5; // Set the line width to 5 pixels
// Draw a red X using lines
x1 = 0; y1 = 0;
x2 = 500; y2 = 400;
x3 = 500; y3 = 0;
x4 = 0; y4 = 400;
ctx.moveTo(x1, y1); // Move to the starting point
ctx.lineTo(x2, y2); // Draw a line to the ending point
ctx.moveTo(x3, y3); // Move to another point
ctx.lineTo(x4, y4); // Draw another line to the ending point
ctx.stroke(); // Display the lines on the canvas
}
// Function to erase all
function eraseAll(){
const sketch2 = document.querySelector('#field1'); // Get the same canvas element with the id 'field1'
if (!sketch2.getContext) { return; } // Check if the canvas is supported in the browser
const ctx2 = sketch2.getContext('2d'); // Get the 2D drawing context of the canvas
ctx2.clearRect(0, 0, sketch2.width, sketch2.height); // Clear the entire canvas
}
</script> 
// Contributor: GeneralAstronomy110@gmail.com

No comments:

Post a Comment

N-point Star in Microsoft Visual Studio Console App

#include <windows.h> #include <cmath> #include <iostream> LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam,...