Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use <canvas> as a CSS background

Can I use the canvas element as a css background?

like image 873
Ben Shelock Avatar asked Aug 03 '10 14:08

Ben Shelock


People also ask

Can you style canvas with CSS?

Because the canvas is an HTML element, you can use CSS styles to modify its position, assign it a background color or image, add a border, and so on. In Safari and other WebKit-based browsers, you can use WebKit transitions to smoothly animate changes in CSS properties.

Is canvas a CSS?

In Canvas the code we have access to uses two languages, HTML (HyperText Markup Language) and CSS (Cascading Style Sheets).

Can you put a canvas in a div?

To add a scrollable canvas inside a div, we can make the div scrollable and put a canvas inside it. to add a div with the overflow CSS property set to auto . And then we add a canvas inside it with a red border.

Is canvas HTML or CSS?

What is HTML Canvas? The HTML <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript). The <canvas> element is only a container for graphics. You must use a script to actually draw the graphics.


1 Answers

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.

like image 109
livedo Avatar answered Oct 05 '22 17:10

livedo