I (14) am working on my first Obsidian extension. It is the first time using TypeScript, and I don’t have a lot of experience with JavaScript. I’m wanting to build an extension, that changes a p5.js code block, into a HTML element with the p5 code rendered in it. I figured out how to replace the codeblock for an HTML element, but i can’t get the js code to run. Not only when it contains p5, also when trying to console.log()
. I’m probably missing something very obvious, but with this as my first non-python/html project, i really can’t find what I’m doing wrong.
The HTML part itself did work when i opened it in my browser, but when adding this code as an HTML element in Obsidian, the JavaScript didn’t run.
The working HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>p5.js Sketch</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
</head>
<body>
<h1>p5.js Sketch</h1>
<div id="sketch-container"></div>
<script>
function setup() {
createCanvas(400, 400);
}
function draw(){
background(220);
ellipse(mouseX, mouseY, 50, 50);
}
new p5(function(sketch) {
sketch.setup = setup;
sketch.draw = draw;
}, 'sketch-container');
</script>
</body>
</html>
The code block marked p5js with ```p5js
in Obsidian:
function setup() {
createCanvas(400, 400);
}
function draw() {
if (mouseIsPressed) {
fill(0);
} else {
fill(255);
}
ellipse(mouseX, mouseY, 80, 80);
}
The entire main.ts
file:
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian';
import p5 from "p5";
export default class MyPlugin extends Plugin {
async onload() {
this.registerMarkdownCodeBlockProcessor('p5js', (source, el) => {
const code = source.trim();
// Replace the code block with a basic HTML structure
el.innerHTML = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>p5.js Sketch</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
</head>
<body>
<h1>p5.js Sketch</h1>
<div id="sketch-container"></div>
<script>
${code}
new p5(function(sketch) {
sketch.setup = setup;
sketch.draw = draw;
}, 'sketch-container');
</script>
</body>
</html>
`;
});
}
}