问题
I'm trying to insert created canvas to the div element to the manually created page template in wordpress:
template-custom.php
<?php get_header('custom') ?>
<div id='createdCanvas' width='600px' height='600px'></div>
<?php get_footer() ?>
sketch.js
function setup() {
var WIDTH = 500;
var HEIGHT = 500;
var myCanvas = createCanvas(WIDTH, HEIGHT);
myCanvas.parent('createdCanvas');
}
I've wrote it by the p5js reference. The canvas displayed on the page, but by default at the of the page. Just one single html page work the same.
So I've tried different couple of different ways to solve it, but nothing is working for me.
The goal is to insert canvas to specified place.
回答1:
There are two ways to do this. One is to write your sketch as a factory, like so:
var sketch = function(p) {
p.setup = function () {
var WIDTH = 500;
var HEIGHT = 500;
p.createCanvas(WIDTH, HEIGHT);
}
/* The rest of your sketch goes here. */
p.draw = function() {
/* draw code here */
}
};
new p5(sketch, document.getElementById('createdCanvas'));
This was the way I had it in my first answer; the issue you had was due to a typo on my part--I didn't prepend the "p." before createCanvas. All p5 global functions will need this "p." if you use this method.
A tidier way of doing it is closer to the way you did it initially. I think you had it, except that you were loading your sketch in -- before the containing had rendered. Try this:
sketch.js:
function setup() {
var WIDTH = 500;
var HEIGHT = 500;
var myCanvas = createCanvas(WIDTH, HEIGHT);
myCanvas.parent('createdCanvas');
}
The template should be the same either way--with the script tag below the containing :
<?php get_header('custom') ?>
<div id='createdCanvas' width='600px' height='600px'>
</div>
<script src="sketch.js"></script>
<?php get_footer() ?>
来源:https://stackoverflow.com/questions/41126331/p5js-sketch-inside-wordpress-page