Use <canvas> as a CSS background
This has been possible in WebKit since 2008, see here.
<html>
<head>
<style>
div { background: -webkit-canvas(squares); width:600px; height:600px; border:2px solid black }
</style>
<script type="application/x-javascript">
function draw(w, h) {
var ctx = document.getCSSCanvasContext("2d", "squares", w, h);
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (30, 30, 55, 50);
}
</script>
</head>
<body onload="draw(300, 300)">
<div></div>
</body>
</html>
Currently, Firefox 4 contains a feature, which allows you to use any element (including canvas) as a CSS background, in this fashion:
<p id="myBackground1" style="background: darkorange; color: white; width: 300px; height: 40px;">
This element will be used as a background.
</p>
<p style="background: -moz-element(#myBackground1); padding: 20px 10px; font-weight: bold;">
This box uses #myBackground1 as its background!
</p>
See Mozilla hacks for specifics.
How do you make a CSS background a Javascript Canvas?
There's a new(ish) API called CSS Houdini that allows you to do exactly what you wanted: https://developer.mozilla.org/en-US/docs/Web/API/PaintWorklet. It's browser support is still super minimal (chromium only currently). There is a pollyfill that should help expand support if needed.
Here's an overview of houdini
There's also an answer with this in the previous stack overflow answers: use canvas as a css background. The links from that answer are incredibly helpful. Especially (two links down) https://twitter.com/DasSurma/status/983305990731894785, which gave an example of how to get the API to work without importing a separate file.
if ("paintWorklet" in CSS) { const src = document.querySelector('script[language$="paint"]').innerHTML; const blob = new Blob([src], { type: 'text/javascript' }); CSS.paintWorklet.addModule(URL.createObjectURL(blob));}
.squares { background-image: paint(squares); width: 200px; height: 200px; border: 2px solid black;}
.checkboxes { background-image: paint(checkerboard); width: 200px; height: 200px; border: 2px solid black; --checkerboard-spacing: 10; --checkerboard-size: 32;}
<div style="display:flex;"> <div class="squares"> </div> <div class="checkboxes"> </div></div><script language="javascript+paint"> class SquaresPainter { paint(ctx, gemetry, properties) { ctx.fillStyle = 'rgb(200,0,0)'; ctx.fillRect(10, 10, 55, 50);
ctx.fillStyle = 'rgba(0, 0, 200, 0.5)'; ctx.fillRect(30, 30, 55, 50); } } registerPaint('squares', SquaresPainter); // checkerboard.js from https://developers.google.com/web/updates/2018/01/paintapi class CheckerboardPainter { // inputProperties returns a list of CSS properties that this paint function gets access to static get inputProperties() { return ['--checkerboard-spacing', '--checkerboard-size']; }
paint(ctx, geom, properties) { // Paint worklet uses CSS Typed OM to model the input values. // As of now, they are mostly wrappers around strings, // but will be augmented to hold more accessible data over time. const size = parseInt(properties.get('--checkerboard-size').toString()); const spacing = parseInt( properties.get('--checkerboard-spacing').toString() ); const colors = ['red', 'green', 'blue']; for (let y = 0; y < geom.height / size; y++) { for (let x = 0; x < geom.width / size; x++) { ctx.fillStyle = colors[(x + y) % colors.length]; ctx.beginPath(); ctx.rect(x * (size + spacing), y * (size + spacing), size, size); ctx.fill(); } } } } registerPaint('checkerboard', CheckerboardPainter);</script>
Set HTML Canvas as page background
canvas {
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
z-index:-1;
}
I am unable to use canvas as background
If you want to use canvas as a background so you can use layering concept. you can adjust canvas layer behind main layer. You can help from this code -
// html
<section>
<canvas id="canvas" height="300" width="300"></canvas>
<div></div>
</section>
//css
section {
position: relative;
}
canvas {
border: 1px solid;
position: absolute;
}
div {
height: 300px;
width: 300px;
position: absolute;
border: 1px solid red;
}
//js
var dom = document.getElementById("canvas");
var ctx = dom.getContext("2d");
ctx.fillRect(100, 100, 100, 100);
How do I make an image appear above the background in html canvas?
Building on the comment from @AHaworth:
you need to be careful about the order in which things are drawn!
The problem I see in your code is on function updateGameArea()
the background should be at the top of the stuff you do, see my fix below.
var myGamePiece;
var myObstacles = [];
var myBackground;
function startGame() {
myGamePiece = new component(50, 50, "red", 10, 60, "rect");
myBackground = new component(1600, 400, "blue", 0, 0, "rect");
myGameArea.start();
}
function updateGameArea() {
myGameArea.clear();
myGameArea.frameNo += 1;
myBackground.speedX = -1;
myBackground.newPos();
myBackground.update();
if (myGameArea.frameNo == 1 || everyinterval(150)) {
myObstacles.push(new component(30, 30, "pink", myGameArea.canvas.width, 50, "rect"))
}
for (i = 0; i < myObstacles.length; i += 1) {
myObstacles[i].x += -0.5;
myObstacles[i].update();
}
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
myGamePiece.newPos();
myGamePiece.update();
}
//board
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 400;
this.canvas.height = 150;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y, type) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
}
function everyinterval(n) {
return ((myGameArea.frameNo / n) % 1 == 0)
}
startGame()
Setting up Background image for a canvas
You can set background image using css and you should give width and height property as well. Please see my demo below.
#canvas{ color: #0cff15; background-image: url("http://www.backgroundsy.com/file/dust-background.jpg"); -webkit-background-image: url("http://www.backgroundsy.com/file/dust-background.jpg"); border:1px solid black; width:500px; height:500px;}
<canvas id="canvas"></canvas>
An html5 canvas element in the background of my page?
You could try setting a CSS style on the canvas where it has a position: fixed
(or absolute
as appropriate), and then any content that follows it (as opposed to container content as you've given in your example) should sit on top of it.
Related Topics
Document.Write() Overwriting the Document
How to Write in File (User Directory) Using JavaScript
JavaScript Data Grid For Millions of Rows
Drag Drop Files into Standard HTML File Input
Play an Audio File Using Jquery When a Button Is Clicked
How to Re-Trigger a Webkit CSS Animation Via JavaScript
Get Local Href Value from Anchor (A) Tag
Html 5 Video or Audio Playlist
How to Detect "Shift+Enter" and Generate a New Line in Textarea
Relative Paths in JavaScript in an External File
JavaScript Dom: Find Element Index in Container
Programmatically Trigger "Select File" Dialog Box
Benefits of Loading Js At the Bottom as Opposed to the Top of the Document
Dynamically Creating HTML Elements Using JavaScript
How to Display JavaScript Variables in a HTML Page Without Document.Write
How to Set Focus on an Element in an HTML Form Using JavaScript