JGeorgeJ
JGeorgeJ

Reputation: 383

Insert canvas inside div with js

I have this part of code

const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
let windowWidth = canvas.width = window.innerWidth;
let windowHeight = canvas.height = window.innerHeight;
canvas.id = 'canvas';
document.body.insertBefore(canvas, document.body.firstChild);

problem is that i am unable to add it inside a div for example <div class="ip_first_block">CANVAS SHOULD BE HERE</div> I am really on beginning of my js path so i am mostly putting togehter parts and editing them.

This is the part a need to change but i cant find the right way

document.body.insertBefore(canvas, document.body.firstChild);

This is one of my tries...

var canvas = document.createElement('canvas');
var firstblock = document.getElementsById('ifb');
var context = canvas.getContext('2d');
var windowWidth = canvas.width = window.innerWidth;
var windowHeight = canvas.height = window.innerHeight;
canvas.id = 'canvas';
firstblock.innerHTML += canvas;

Upvotes: 3

Views: 3165

Answers (1)

Naoric
Naoric

Reputation: 355

canvas is an element and not a string. You should use the proper API to append it as a child: firstblock.appendChild(canvas)

document.addEventListener('DOMContentLoaded', () => {
  var canvas = document.createElement('canvas')

  var container = document.querySelector('.ip_first_block')

  container.appendChild(canvas)

})

Upvotes: 1

Related Questions