JSFiddle - React, Tailwind, and code Playground
by Hui Zheng
HTML
<canvas id="myCanvas" width="300" height="150">
Fallback content, in case the browser does not support Canvas.
</canvas>
JavaScript
// Get a reference to the element.
var elem = document.getElementById('myCanvas');
// Always check for properties and methods, to make sure your code doesn't break
// in other browsers.
if (elem && elem.getContext) {
// Get the 2d context.
// Remember: you can only initialize one context per element.
var context = elem.getContext('2d');
if (context) {
// You are done! Now you can draw your first rectangle.
// You only need to provide the (x,y) coordinates, followed by the width and
// height dimensions.
context.fillRect(0, 0, 150, 100);
context.fillStyle = '#00f'; // blue
context.strokeStyle = '#f00'; // red
context.lineWidth = 4;
// Draw some rectangles.
context.fillRect(0, 0, 150, 50);
context.strokeRect(0, 60, 150, 50);
context.clearRect(30, 25, 90, 60);
context.strokeRect(30, 25, 90, 60);
// Set the style properties.
context.fillStyle = '#00f';
context.strokeStyle = '#f00';
context.lineWidth = 4;
context.beginPath();
// Start from the top-left point.
context.moveTo(10, 10); // give the (x,y) coordinates
context.lineTo(100, 10);
context.lineTo(10, 100);
context.lineTo(10, 10);
// Done! Now fill the shape, and draw the stroke.
// Note: your shape will not be visible until you call any of the two methods.
context.fill();
context.stroke();
context.closePath();
}
}