How do I make the JavaScript canvas cover the whole screen? - javascript

(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 || "black");
// 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 = 40; // or whatever
var fillColor = '#ff0000';
ctx.globalCompositeOperation = 'destination-out';
ctx.fillCircle(x, y, radius, fillColor);
};
canvas.node.onmousedown = function(e) {
canvas.isDrawing = false;
};
canvas.node.onmouseup = function(e) {
canvas.isDrawing = true;
};
}
var container = document.getElementById('canvas');
init(container, 531, 438, 'black');
})();
#canvas {
/* background:url(); */
width: 100vw;
height: 100vh;
background-color: rgb(224, 255, 226);
}
<div id="canvas"></div>
I'm starting out quite new to coding, I'm trying to get the JavaScript to cover the whole of the rgb(224, 255, 226) - that mint looking color. So basically I want to whole thing back. Please help and thank you in advance for the help :)
This is code I found on the internet, I tried to find the person that made it to ask them but they did not reply

When you call init(), instead of passing static values for width and height, pass the size of the window.
(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 || "black");
// 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 = 40; // or whatever
var fillColor = '#ff0000';
ctx.globalCompositeOperation = 'destination-out';
ctx.fillCircle(x, y, radius, fillColor);
};
canvas.node.onmousedown = function(e) {
canvas.isDrawing = false;
};
canvas.node.onmouseup = function(e) {
canvas.isDrawing = true;
};
}
var container = document.getElementById('canvas');
// Instead of passing static values for width and height,
// pass the size of the window.
init(container, window.innerWidth, window.innerHeight, 'black');
})();
#canvas {
/* background:url(); */
width: 100vw;
height: 100vh;
background-color: rgb(224, 255, 226);
}
<div id="canvas" height="50" width="50"></div>

You need to pass window.innerWidth and window.innerHeight as parameters to init function.
(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 || "black");
// 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 = 40; // or whatever
var fillColor = '#ff0000';
ctx.globalCompositeOperation = 'destination-out';
ctx.fillCircle(x, y, radius, fillColor);
};
canvas.node.onmousedown = function(e) {
canvas.isDrawing = false;
};
canvas.node.onmouseup = function(e) {
canvas.isDrawing = true;
};
}
var container = document.getElementById('canvas');
init(container, window.innerWidth, window.innerHeight, 'black');
})();
<div id="canvas"></div>

Related

Make erase work for thoughscreen (TouchEvent)

i made a simple game where you have to erase a colored layer to reveal a image. But it only works on my desktop, not on something with a thoughscreen (iphone or ipad). I know i have to replace the MouseEvent to TouchEvent but i don't know how since i am a beginner at coding. I hope someone can help me with this!
#canvas {
background-image: url("img/image.jpg");
background-repeat: no-repeat;
width: 800px;
height: 800px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Ellen Langendam</title>
<link href="style.css" rel="stylesheet">
</head>
<body>
<div id="canvas"></div>
<script>
(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 * 10, 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 = 40; // or whatever
var fillColor = '#ff0000';
ctx.globalCompositeOperation = 'destination-out';
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, 800, 800, '#99ff99');
})();
</script>
</body>
</html>
Register touch movements with ontouchmove and then interate through the touch points event.touches and use the properties from each of those items to draw your circle, the same way you do it in onmousemove.
I would also suggest turning to using let or const type of variables rather than var as var's can result in unfortunate issues, see: What's the difference between using "let" and "var"?
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 * 10, 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 = 40; // or whatever
var fillColor = '#ff0000';
ctx.globalCompositeOperation = 'destination-out';
ctx.fillCircle(x, y, radius, fillColor);
};
canvas.node.onmousedown = function(e) {
canvas.isDrawing = true;
};
canvas.node.onmouseup = function(e) {
canvas.isDrawing = false;
};
canvas.node.ontouchmove = function(event) {
for(let index = 0; index < event.touches.length; index++) {
const touch = event.touches[index];
const x = touch.pageX - this.offsetLeft;
const y = touch.pageY - this.offsetTop;
const radius = 40; // or whatever
const fillColor = '#ff0000';
ctx.globalCompositeOperation = 'destination-out';
ctx.fillCircle(x, y, radius, fillColor);
}
};
}
var container = document.getElementById('canvas');
init(container, 800, 800, '#99ff99');
#canvas {
background-image: url("img/image.jpg");
background-repeat: no-repeat;
width: 800px;
height: 800px;
}
<div id="canvas"></div>

trying to add a photo instead of color

(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 || "yel");
// 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 = 40; // or whatever
var fillColor = '#ff0000';
ctx.globalCompositeOperation = 'destination-out';
ctx.fillCircle(x, y, radius, fillColor);
};
canvas.node.onmousedown = function(e) {
canvas.isDrawing = false;
};
canvas.node.onmouseup = function(e) {
canvas.isDrawing = true;
};
}
var img = document.createElement("img");
img.src= "blm.jpg";
var container = document.getElementById('canvas');
init(container, window.innerWidth, window.innerHeight, 'img');
})();
Hi im trying to make a cover for my canvas instead of just a plain black color on my code. instead i would like my image named "blm.jpg" to replace the plain black. Im not sure how to. Im very new to coding and would really appreciate any help that i can get :) I added the var img = document 5 lines from the bottom and the 4th line from the bottom, im not sure if thats meant to be there either.
thank you for any help in advance :)
Here is a simple example on how to do that, I'm just drawing grids over the background image
var canvas = document.querySelector("canvas"),
ctx = canvas.getContext("2d"),
backgroundImage = document.createElement("img");
backgroundImage.src = "https://openclipart.org/image/400px/svg_to_png/260587/Surreal-Fantastic-Nature.png";
function makeLine(start_x, start_y, end_x, end_y) {
ctx.moveTo(start_x, start_y);
ctx.lineTo(end_x, end_y);
}
function drawGrid(val, color) {
ctx.beginPath();
ctx.strokeStyle = color;
for(var i = 0; i <= canvas.height; i += val) {
makeLine(0, i, canvas.width, i);
}
for(var j = 0; j <= canvas.width; j += val) {
makeLine(j, 0, j, canvas.height);
}
ctx.stroke();
}
// draw it first to make it the background and only when it loads
backgroundImage.onload = function() {
ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
drawGrid(10, "blue");
drawGrid(20, "red");
drawGrid(40, "black");
}
canvas {
border-radius: 3px;
box-shadow: 1px 1px 10px blue;
}
<canvas width="320" height="200">
You may noticed that we need to wait for the image to load for drawing it and draw other stuff, but here is another way by wrapping the whole code into the window.onload method and add our image as an HTML element and hide it of course
window.onload = function() {
var canvas = document.querySelector("canvas"),
ctx = canvas.getContext("2d"),
backgroundImage = document.querySelector("#background-img");
function makeLine(start_x, start_y, end_x, end_y) {
ctx.moveTo(start_x, start_y);
ctx.lineTo(end_x, end_y);
}
function drawGrid(val, color) {
ctx.beginPath();
ctx.strokeStyle = color;
for(var i = 0; i <= canvas.height; i += val) {
makeLine(0, i, canvas.width, i);
}
for(var j = 0; j <= canvas.width; j += val) {
makeLine(j, 0, j, canvas.height);
}
ctx.stroke();
}
// no need for the .onload since the code is executing after everything loads
ctx.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height);
drawGrid(10, "blue");
drawGrid(20, "red");
drawGrid(40, "black");
}
canvas {
border-radius: 3px;
box-shadow: 1px 1px 10px blue;
}
.hidden {
display: none;
}
<canvas width="320" height="200"></canvas>
<img id="background-img" class="hidden" src="https://openclipart.org/image/400px/svg_to_png/260587/Surreal-Fantastic-Nature.png" alt="nature painting">

How to make mousemove event working for touchscreen with touchmove?

I'm working on a canvas javascript where with the mousemove event you can erase the background...
Now i'm trying to get the same experience for touchscreens (mobile).
How can I give my code the mousemove and touchmove event at the same time?
(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();*/
var radgrad = ctx.createRadialGradient(x, y, 0, x, y, radius);
radgrad.addColorStop(0, 'rgba(255,0,0,1)');
radgrad.addColorStop(0.8, 'rgba(255,0,0,.9)');
radgrad.addColorStop(1, 'rgba(255,0,0,0)');
// draw shape
ctx.fillStyle = radgrad;
ctx.fillRect(x - radius, y - radius, x + radius, y + radius);
};
ctx.clearTo = function(fillColor) {
ctx.fillStyle = fillColor;
ctx.fillRect(0, 1, 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 = 100; // or whatever
var fillColor = '#ff0000';
ctx.globalCompositeOperation = 'destination-out';
ctx.fillCircle(x, y, radius, fillColor);
};
canvas.node.onmouseenter = function(e) {
canvas.isDrawing = true;
};
}
var container = document.getElementById('canvas');
init(container, 5000, 3000, '#f8fa58');
})();
body {
margin-left: -10vw;
margin-top: -30vh;
background: url(https://i-d-images.vice.com/images/articles/meta/2014/10/21/untitled-article-1413860640.jpg?crop=1xw:0.44513137557959814xh;0xw,0.14219474497681608xh&resize=2000:*&output-format=image/jpeg&output-quality=75) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#canvas {
z-index: -1;
top: 2vh;
left: -10vw;
width: 110vw;
height: 130vh;
overflow: hidden;
}
<div id="back"></div>
<div id="canvas"></div>
You can use the same event handler, but inside, you'll have to process the event differently, because there is no clientX nor clientY property on touch[XXX] events.
Touch events can be multi-touch, so they do hold an array of touches, which have these coordinate properties.
IMO a cleaner way would be to split your event handler in two different phases :
one to extract the event's coordinates, and one to do something with these coords.
(function() {
// a little verbose but...
function handleMousemove(event){
var x = event.clientX;
var y = event.clientY;
draw(x, y);
}
function handleTouchmove(event){
event.preventDefault(); // we don't want to scroll
var touch = event.touches[0];
var x = touch.clientX;
var y = touch.clientY;
draw(x, y);
}
// this one can be shared by both touch and move events
function activateDrawing(event){
event.preventDefault();
canvas.isDrawing = true;
}
function draw(eventX, eventY){
var x = eventX - canvas.node.offsetLeft;
var y = eventY - canvas.node.offsetTop;
if (!canvas.isDrawing) {
return;
}
var radius = 100; // or whatever
var fillColor = '#ff0000';
ctx.globalCompositeOperation = 'destination-out';
ctx.fillCircle(x, y, radius, fillColor);
}
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;
}
var canvas, ctx; // got it out to avoid nesting too deeply my handlers;
function init(container, width, height, fillColor) {
canvas = createCanvas(container, width, height);
ctx = canvas.context;
// define a custom fillCircle method
ctx.fillCircle = function(x, y, radius, fillColor) {
var radgrad = ctx.createRadialGradient(x, y, 0, x, y, radius);
radgrad.addColorStop(0, 'rgba(255,0,0,1)');
radgrad.addColorStop(0.8, 'rgba(255,0,0,.9)');
radgrad.addColorStop(1, 'rgba(255,0,0,0)');
// draw shape
ctx.fillStyle = radgrad;
ctx.fillRect(x - radius, y - radius, x + radius, y + radius);
};
ctx.clearTo = function(fillColor) {
ctx.fillStyle = fillColor;
ctx.fillRect(0, 1, width, height);
};
ctx.clearTo(fillColor || "#ddd");
// bind mouse events
canvas.node.onmousemove = throttle(handleMousemove);
canvas.node.ontouchmove = throttle(handleTouchmove);
canvas.node.onmouseenter =
canvas.node.ontouchstart = throttle(activateDrawing);
}
var container = document.getElementById('canvas');
init(container, 5000, 3000, '#f8fa58');
/* Bonus : throttle these events so they don't fire too often */
function throttle(callback) {
var active = false; // a simple flag
var evt; // to keep track of the last event
var handler = function(){ // fired only when screen has refreshed
active = false; // release our flag
callback(evt);
}
return function handleEvent(e) { // the actual event handler
evt = e; // save our event at each call
if (!active) { // only if we weren't already doing it
active = true; // raise the flag
requestAnimationFrame(handler); // wait for next screen refresh
};
}
}
})();
body {
margin-left: -10vw;
margin-top: -30vh;
background: url(https://i-d-images.vice.com/images/articles/meta/2014/10/21/untitled-article-1413860640.jpg?crop=1xw:0.44513137557959814xh;0xw,0.14219474497681608xh&resize=2000:*&output-format=image/jpeg&output-quality=75) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#canvas {
z-index: -1;
top: 2vh;
left: -10vw;
width: 110vw;
height: 130vh;
overflow: hidden;
}
<div id="back"></div>
<div id="canvas"></div>

How do I erase image with cursor to reveal another image?

Okay, so I know there is a similar post to this (javascript erase image with cursor) but I've seen it and the code linked in the answers and I was wondering if there was a way to edit the code so that instead of erasing a solid color to reveal an image, I could erase an image to reveal a different image.
This is the code/markup from the site.
HTML
<div id="canvas"></div>
CSS
#canvas {
background:url(http://www.topscratchcards.com/images/games/888ladies/scratchcard-winning-ticket.jpg);
width: 531px;
height: 438px;
}
JAVASCRIPT
(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 = 20; // or whatever
var fillColor = '#ff0000';
ctx.globalCompositeOperation = 'destination-out';
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, 531, 438, '#ddd');
})();
I don't know if there is a way to edit this code to achieve what I want - if there isn't then is there any alternative method/code I could use?
There's an alternative.
You can use .innerHTML to resolve your problem.
eg. take a div with name mydiv
< img id="myImage"
src="http://www.w3schools.com/js/pic_bulboff.gif"
onmouseover="document.getElementById('myImage').src='http://www.w3schools.com/js/pic_bulbon.gif'"
onmouseout="document.getElementById('myImage').src='http://www.w3schools.com/js/pic_bulboff.gif'"
>
Ideally this sould solve your purpose
$("svg").on("mousemove", function (e) {
var x = e.pageX - $("#mySvg").offset().left;
var y = e.pageY - $("#mySvg").offset().top;
// console.log(x);
// console.log(y);
$(".a").attr("cx", x).attr("cy", y);
});
#mySvg {
width: 531px;
height: 438px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<svg id="mySvg">
<clippath id="clip">
<circle cx="-20" cy="-20" r="80" class="a" />
</clippath>
<image preserveAspectRatio="xMidYMin slice"
href="https://www.gannett-cdn.com/presto/2021/03/02/USAT/a51266de-f2dc-404c-a46a-bcca17c496eb-matrix-reloaded-keanu-reeves.png?width=660&height=372&fit=crop&format=pjpg&auto=webp"
class="one" />
<image preserveAspectRatio="xMidYMin slice" href="https://static.dw.com/image/56167112_303.jpg"
clip-path="url(#clip)" />
</svg>

HTML5 canvas, save as image, toDataURL(), create ID

I have this little JavaScript canvas snippet:
(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');
})();
Now it takes the div with the id of canvas, and creates a little HTML5 canvas 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 canvas.toDataURL()? As far as I know, I would have to take the canvas, and do the canvas.toDataURL() to save it to an image. But- that needs an ID right? SOOOO when I created the canvas in the createCanvas function, how would I make an id accompanying it, so I could do something like document.getElementById("idofcanvas").toDataURL() ?
Thank you in advance for your help! :)
But- that needs an ID right?
It doesn't need an ID, but an ID won't hurt (so long as it's actually unique ;-)). Any method to select a DOM element will work here. If there's only one canvas on the page, this would suffice, for example:
var canvas = document.getElementsByTagName('canvas')[0];
var imageData = canvas.toDataURL();
When I created the canvas in the createCanvas function, how would I make an id accompanying it?
You'd just set the ID property of the canvas element before returning it. Remember, you need to ensure that this value is unique!
function createCanvas(parent, width, height) {
var canvas = {};
canvas.node = document.createElement('canvas');
canvas.node.id = /* some unique value here */;
canvas.context = canvas.node.getContext('2d');
canvas.node.width = width || 100;
canvas.node.height = height || 100;
parent.appendChild(canvas.node);
return canvas;
}

Categories