user1137313
user1137313

Reputation: 2410

Draw on HTML5 canvas and use the drawing as a div

Is it possible to draw on the canvas using HTML5 and other js libraries and use the resulting drawing as a div?

I am interested in achieving a box (for starters) that is not drawn by regular css borders, but by a shape drawn on the canvas. Is that possible? And how?

I found paper.js on google, but that is all about drawing. How to use that drawing as a div in regular HTML (5) is my question. Thank you

Upvotes: 1

Views: 3705

Answers (2)

user1693593
user1693593

Reputation:

You can draw your shape on canvas (using paper.js or plain JavaScript) then extract it as an image which you set as background to a div or other element.

Just have in mind that you need to update the background if the div's size changes.

var canvas = document.createElement('canvas'),
    div = document.getElementById('myDivElement'),
    ctx = canvas.getContext('2d'),
    cs = getComputedStyle(div),
    w = parseInt(cs.getPropertyValue('width') , 10),
    h = parseInt(cs.getPropertyValue('height') , 10);

canvas.width = w;
canvas.height = h;

/// draw something on canvas
ctx.lineWidth = 5;
ctx.strokeStyle = '#f90';
ctx.strokeRect(0, 0, w, h);

/// set as background:
div.style.backgroundImage = 'url(' + canvas.toDataURL() + ')';

Online demo

Just note that many things can affect the div size such as padding, margin, box-sizing, borders etc. These you need to take into account when you are calculating the size of the canvas. The better option is in many cases to use box-sizing: border-box; for the CSS rule of the element in question.

Upvotes: 1

No Surprises
No Surprises

Reputation: 4901

canvas is a DOM element in which you can draw arbitrary vector and raster graphics. div is another type of DOM element that can contain other elements, like canvas for example.

The graphics that you draw in a canvas elements are not DOM elements that you can interact with the same way as div, span, p, table, etc. So I think the answer to your question is no.

Upvotes: 0

Related Questions