JSFiddle - React, Tailwind, and code Playground
by Nick Karnik
HTML
<canvas id=world width="640px" height="480px"></canvas>
CSS
canvas {
//width: 640px;
//height: 480px;
border: 1px solid black;
background-color: black;
}
JavaScript
var canvas = document.getElementById('world');
var ctx = canvas.getContext('2d');
function writeMessage(message) {
ctx.clearRect(0, 0, 400, 100);
ctx.font = '18pt Calibri';
ctx.fillStyle = 'white';
ctx.fillText(message, 10, 25);
}
function getMousePos(e){
var rect = canvas.getBoundingClientRect();
return {
x: e.clientX - rect.left,
y: e.clientY - rect.top
}
}
document.addEventListener('mousemove', function(e) {
var mousePos = getMousePos(e);
var message = 'Mouse Position: ' + mousePos.x + ', ' + mousePos.y;
writeMessage(message);
RenderCube(mousePos.x, mousePos.y);
});
//var width = 100, height=100; depth = 100;
ctx.fillStyle = 'yellow';
ctx.strokeStyle = 'yellow';
var length = 100;
function RenderCube(x, y) {
//ctx.fillStyle = 'green';
//ctx.fillRect(0, 0, 100, 100);
ctx.clearRect(0, 100, canvas.width, canvas.height);
//topleft
RenderPoint(x, y);
//topright
RenderPoint(x+length, y);
//bottomleft
RenderPoint(x, y+length);
//bottomright
RenderPoint(x+length, y+length);
//top
RenderLine(x, y, x+length, y);
//left
RenderLine(x, y, x, y+length);
//bottom
RenderLine(x, y+length, x+length, y+length);
//right
RenderLine(x+length, y, x+length, y+length);
}
function RenderLine(x1, y1, x2, y2)
{
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
function RenderScene() {
RenderCube(250, 250, 50);
}
var radius = 5;
function RenderPoint(x, y) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
//ctx.stroke();
ctx.fill();
}
window.requestAnimationFrame(RenderScene);