Note that there are some explanatory texts on larger screens.

plurals
  1. POHTML5 canvas, save as image, toDataURL(), create ID
    primarykey
    data
    text
    <p>I have this little JavaScript canvas snippet:</p> <pre><code>(function() { // Creates a new canvas element and appends it as a child // to the parent element, and returns the reference to // the newly created canvas element function createCanvas(parent, width, height) { var canvas = {}; canvas.node = document.createElement('canvas'); canvas.context = canvas.node.getContext('2d'); canvas.node.width = width || 100; canvas.node.height = height || 100; parent.appendChild(canvas.node); return canvas; } function init(container, width, height, fillColor) { var canvas = createCanvas(container, width, height); var ctx = canvas.context; // define a custom fillCircle method ctx.fillCircle = function(x, y, radius, fillColor) { this.fillStyle = fillColor; this.beginPath(); this.moveTo(x, y); this.arc(x, y, radius, 0, Math.PI * 2, false); this.fill(); }; ctx.clearTo = function(fillColor) { ctx.fillStyle = fillColor; ctx.fillRect(0, 0, width, height); }; ctx.clearTo(fillColor || "#ddd"); // bind mouse events canvas.node.onmousemove = function(e) { if (!canvas.isDrawing) { return; } var x = e.pageX - this.offsetLeft; var y = e.pageY - this.offsetTop; var radius = 10; // or whatever var fillColor = '#ff0000'; ctx.fillCircle(x, y, radius, fillColor); }; canvas.node.onmousedown = function(e) { canvas.isDrawing = true; }; canvas.node.onmouseup = function(e) { canvas.isDrawing = false; }; } var container = document.getElementById('canvas'); init(container, 200, 200, '#ddd'); })(); </code></pre> <p>Now it takes the div with the <code>id</code> of <code>canvas</code>, and creates a little HTML5 <code>canvas</code> inside it, where the user can basically draw with their mouse. NOW thats nice... but what if I had to save whats inside the canvas with <code>canvas.toDataURL()</code>? As far as I know, I would have to take the canvas, and do the <code>canvas.toDataURL()</code> to save it to an image. But- that needs an ID right? SOOOO when I created the canvas in the <code>createCanvas</code> function, how would I make an <code>id</code> accompanying it, so I could do something like <code>document.getElementById("idofcanvas").toDataURL()</code> ?</p> <p>Thank you in advance for your help! :)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload