JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas" width=400 height=400></canvas>
JavaScript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cWidth = canvas.width;
var cHeight = canvas.height;
CanvasRenderingContext2D.prototype.dashedLine = function (x1, y1, x2, y2, dashLength) {
dashLength = dashLength === undefined ? 5 : dashLength;
var deltaX = x2 - x1;
var deltaY = y2 - y1;
var numDashes = Math.floor(
Math.sqrt(deltaX * deltaX + deltaY * deltaY) / dashLength);
for (var i = 0; i < numDashes; ++i) {
ctx[i % 2 === 0 ? 'moveTo' : 'lineTo']
(x1 + (deltaX / numDashes) * i, y1 + (deltaY / numDashes) * i);
}
}
function render() {
ctx.clearRect(0, 0, cWidth, cHeight);
renderBackground();
// Rest removed for brevity
}
function renderBackground() {
ctx.lineWidth = 5;
ctx.strokeStyle = '#FF0000';
ctx.fillStyle = '#0000ff';
ctx.fillRect(0, 0, cWidth, cHeight);
ctx.beginPath(); // <-- here
ctx.dashedLine(0, 0, 0, cHeight, 10);
ctx.stroke()
}
function animLoop() {
render();
requestAnimationFrame(animLoop);
}
window.requestAnimationFrame = (function () {
return (
window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60);
});
})();
requestAnimationFrame(animLoop);