Add Clear button to canvas - javascript

I've been having a hard time adding a clear canvas button. I'm trying to build a simple canvas where the user can draw and download the images they've made.
I don't know a lot about javascript (nor html and css to be honest) and have looked into similar questions and tried different solutions but just can't seem to get it to work?
Can anyone help out?
Thank you so much in advance
Beatriz
canvas {
cursor: url(cursor.png), crosshair;
border-top: 2px solid #000000;
width: 100vw;
height: 100vh;
background-image: url(posters_v3.png);
background-size: contain;
margin: 0 0 85px 0;
}
input.button {
position:absolute;
}
<section class="canvas">
<canvas id="canvas" style="position:absolute;border-top:2px solid;"></canvas>
<div>
<input type="button" id="clear" value="Clear">
</div>
<script>
const canvas = document.querySelector('#canvas');
// could be 3d
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.lineWidth = 10;
ctx.strokeStyle = '#000000';
let isDrawing = false;
let lastX = 0;
let lastY = 0;
function draw(e) {
// stop the function if they are not mouse down
if(!isDrawing) return;
//listen for mouse move event
console.log(e);
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
[lastX, lastY] = [e.offsetX, e.offsetY];
}
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mouseout', () => isDrawing = false);
</script>

You need to add an other event listener and use the method ctx.clearRect(); The clear rect should be as big as your canvas.
Maybe you couldn't do it because your button was underneath the canvas thus unclickable.
const canvas = document.querySelector('#canvas');
// could be 3d
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.lineWidth = 10;
ctx.strokeStyle = '#000000';
let isDrawing = false;
let lastX = 0;
let lastY = 0;
function draw(e) {
// stop the function if they are not mouse down
if(!isDrawing) return;
//listen for mouse move event
//console.log(e);
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
[lastX, lastY] = [e.offsetX, e.offsetY];
}
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mouseout', () => isDrawing = false);
_clear.addEventListener("click", ()=>{
ctx.clearRect(0,0,canvas.width,canvas.height)
})
<section class="canvas">
<canvas id="canvas" style="border:2px solid; "></canvas>
<div>
<input type="button" id="_clear" value="Clear" style="position:absolute;top:0;left:0">
</div>
</section>

Related

I'm trying to make a javascript drawing program within the browser and things are misaligned. Is there something wrong with my code?

I've been working on this really basic drawing program for a while now and just can't seem to get it to work correctly.
The user can draw in the canvas element now, but things are somehow misaligned; the lines appear far from the cursor when you attempt to draw, and I'm not sure what's causing it.
Here's my code...
html
<div class="info">
<canvas id="canvas" height="480" width="640" style="border:1px solid #000000; width: 640px; height:480px; background-color: white">Please update your browser.</canvas>
<script src="paint.js"></script>
</div>
javascript
// paint.js
(function () {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
//resizing
//canvas.height = window.innerHeight;
//canvas.width = window.innerWidth;
//variables
var painting = false;
function startPosition(e) {
painting = true;
draw(e);
}
function endPosition() {
painting = false;
context.beginPath();
}
function draw(e) {
if (!painting) return;
context.lineWidth = 7;
context.lineCap = "round";
context.strokeStyle = "green";
context.lineTo(e.clientX, e.clientY);
context.stroke();
context.beginPath();
context.moveTo(e.clientX, e.clientY);
}
//EventListeners
canvas.addEventListener("mousedown", startPosition);
canvas.addEventListener("mouseup", endPosition);
canvas.addEventListener("mousemove", draw);
})();
change the clientX and clientY with offsetX and offsetY to get the right coords according to mouse position inside the element
you can read more about MouseEvent and figure out the differences between
clientX/Y
screenX/Y
offsetX/Y
try the snippet
// paint.js
(function () {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
//resizing
//canvas.height = window.innerHeight;
//canvas.width = window.innerWidth;
//variables
var painting = false;
function startPosition(e) {
painting = true;
draw(e);
}
function endPosition() {
painting = false;
context.beginPath();
}
function draw(e) {
if (!painting) return;
context.lineWidth = 4;
context.lineCap = "round";
context.strokeStyle = "green";
context.lineTo(e.offsetX, e.offsetY);
context.stroke();
context.beginPath();
context.moveTo(e.offsetX, e.offsetY);
}
//EventListeners
canvas.addEventListener("mousedown", startPosition);
canvas.addEventListener("mouseup", endPosition);
canvas.addEventListener("mousemove", draw);
})();
div {
width: 460px;
height: 460px;
border: 1px solid black;
}
<div class="info">
<canvas id="canvas" height="460" width="460" style="border:1px solid #000000; background-color: white">Please update your browser.</canvas>
<script src="paint.js"></script>
</div>

HTML5 canvas drawing board - touch support

I am using this simple script to enable users to enter their signatures. Unfortunately, this does not work on mobile devices.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var container = document.getElementById('container');
var container_style = getComputedStyle(container);
canvas.width = 400;
canvas.height = 300;
var mouse = {x: 0, y: 0};
canvas.addEventListener('mousemove', function(e) {
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
}, false);
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = "black";
function getSize(size){ctx.lineWidth = size;}
canvas.addEventListener('mousedown', function(e) {
ctx.beginPath();
ctx.moveTo(mouse.x, mouse.y);
canvas.addEventListener('mousemove', onPaint, false);
}, false);
canvas.addEventListener('mouseup', function() {
canvas.removeEventListener('mousemove', onPaint, false);
}, false);
var onPaint = function() {
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
};
#canvas {
border: 1px solid rgba(0,0,0,.5);
}
<div id="container">
<canvas id="canvas"></canvas>
</div>
Is there an easy way to add touch support to this script?
Make these changes to your code:
Use pointer events (instead of mouse events): pointerdown, pointerup, and pointermove. Pointer events work for both mouse and touch interactions.
Add touch-action: none to your canvas CSS. This prevents the dragging of your finger from triggering the device's panning action (which stops your drawing).
Set your "mouse" coordinates upon pointerdown. This will stop previous lines from being connected to new ones.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var container = document.getElementById('container');
canvas.width = 400;
canvas.height = 300;
var mouse = {x: 0, y: 0};
canvas.addEventListener('pointermove', function(e) {
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
}, false);
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = 'black';
canvas.addEventListener('pointerdown', function(e) {
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
ctx.beginPath();
ctx.moveTo(mouse.x, mouse.y);
canvas.addEventListener('pointermove', onPaint, false);
}, false);
canvas.addEventListener('pointerup', function() {
canvas.removeEventListener('pointermove', onPaint, false);
}, false);
var onPaint = function() {
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
};
#canvas {
border: 1px solid rgba(0,0,0,.5);
touch-action: none;
}
<div id="container">
<canvas id="canvas"></canvas>
</div>

HTML5 canvas paint realistic simple pencil

How i can create realistic simple pencil tool, not like in a ms windows paint program. I need result like this:
if i try solid without transparent i get like in a ms windows paint programs not realistic pencil, if i try add opacity i see circles this is too not realistic:
How i can get pencil tool like in first picture? my trying example:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var previousMouseX = null;
var previousMouse = null;
var isDrawing = false;
var lineWidth = 10;
var brush = 1;
var myColor = "#FF0000";
function getMousePosition(canvas, evt) {
var rect = canvas.getBoundingClientRect();
if (evt.clientX !== undefined && evt.clientY !== undefined) {
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
}
/* BUTTONS */
$("#btn1").on("click", function() {
ctx.globalAlpha = "0.2";
});
$("#btn2").on("click", function() {
ctx.globalAlpha = "1";
});
$("#change-color").on("click", function() {
ctx.strokeStyle = "#009933";
});
$("#canvas").on("mousedown", function(e) {
isDrawing = true;
var pos = getMousePosition(canvas, e);
move(pos.x, pos.y);
});
$("#canvas").on("mousemove", function(e) {
if(isDrawing) {
var pos = getMousePosition(canvas, e);
stroke(pos.x, pos.y);
}
});
$("#canvas").on("mouseup", function() {
isDrawing = false;
});
function stroke(mouseX, mouseY) {
ctx.globalCompositeOperation = "source-over";
ctx.lineJoin = ctx.lineCap = "round";
ctx.lineWidth = 10;
ctx.beginPath();
ctx.moveTo(previousMouseX, previousMouseY);
ctx.lineTo(mouseX, mouseY);
ctx.closePath();
ctx.stroke();
move(mouseX, mouseY);
}
function move(mouseX, mouseY) {
previousMouseX = mouseX;
previousMouseY = mouseY;
}
canvas {
border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" id="btn1" value="Transparent">
<input type="button" id="btn2" value="Solid">
<input type="button" id="change-color" value="Green color"><br />
<canvas id="canvas" width="500" height="500">
Does this go anywhere near doing what you want?
Draw at pencil using transparent, line width 10 and then draw over the line solid using smaller line width (8). Perhaps you could get more variation by randomly varying the second line width between 7, 8 and 9?
EDIT could also randomly set opacity of second line between say 1 and 0.8!
Permanently set opacity on first line and added this code to the function stroke()
ctx.globalAlpha = "1";
ctx.lineWidth = 6;
ctx.beginPath();
ctx.moveTo(previousMouseX, previousMouseY);
ctx.lineTo(mouseX, mouseY);
ctx.closePath();
ctx.stroke();
Changed code snippet
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var previousMouseX = null;
var previousMouse = null;
var isDrawing = false;
var lineWidth = 10;
var brush = 1;
var myColor = "#FF0000";
function getMousePosition(canvas, evt) {
var rect = canvas.getBoundingClientRect();
if (evt.clientX !== undefined && evt.clientY !== undefined) {
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
}
/* BUTTONS */
$("#btn1").on("click", function() {
ctx.globalAlpha = "0.2";
});
$("#btn2").on("click", function() {
ctx.globalAlpha = "1";
});
$("#change-color").on("click", function() {
ctx.strokeStyle = "#009933";
});
$("#canvas").on("mousedown", function(e) {
isDrawing = true;
var pos = getMousePosition(canvas, e);
move(pos.x, pos.y);
});
$("#canvas").on("mousemove", function(e) {
if(isDrawing) {
var pos = getMousePosition(canvas, e);
stroke(pos.x, pos.y);
}
});
$("#canvas").on("mouseup", function() {
isDrawing = false;
});
function stroke(mouseX, mouseY) {
ctx.globalCompositeOperation = "source-over";
ctx.lineJoin = ctx.lineCap = "round";
ctx.lineWidth = 10;
ctx.globalAlpha = "0.2"; //NOTE ALWAYS SET TO 'TRANSPARENT' needs variable if you want to switch to solid.
ctx.beginPath();
ctx.moveTo(previousMouseX, previousMouseY);
ctx.lineTo(mouseX, mouseY);
ctx.closePath();
ctx.stroke();
ctx.globalAlpha = "1";
ctx.lineWidth = 6;
ctx.beginPath();
ctx.moveTo(previousMouseX, previousMouseY);
ctx.lineTo(mouseX, mouseY);
ctx.closePath();
ctx.stroke();
move(mouseX, mouseY);
}
function move(mouseX, mouseY) {
previousMouseX = mouseX;
previousMouseY = mouseY;
}
canvas {
border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" id="btn1" value="Transparent">
<input type="button" id="btn2" value="Solid">
<input type="button" id="change-color" value="Green color"><br />
<canvas id="canvas" width="500" height="500">
Here's a pencil effect.
It's adapted from this nice chalk effect done by Mohamed Moustafa: http://codepen.io/mmoustafa/pen/gmEdk
Example code and a Demo:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw,ch;
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var scrollX=$canvas.scrollLeft();
var scrollY=$canvas.scrollTop();
var isDown=false;
var startX,startY,mouseX,mouseY;
var xLast = 0;
var yLast = 0;
var brushDiameter=2;
var fill1='rgba(255,255,255,0.5)';
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/pad.jpg";
function start(){
cw=canvas.width=img.width;
ch=canvas.height=img.height;
ctx.fillStyle = fill1;
ctx.strokeStyle = fill1;
ctx.lineWidth = brushDiameter;
ctx.lineCap = 'round';
ctx.drawImage(img,0,0);
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
}
function handleMouseDown(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
getOffset();
xLast=mouseX=parseInt(e.clientX-offsetX);
yLast=mouseY=parseInt(e.clientY-offsetY);
isDown=true;
draw(mouseX+1, mouseY+1);
}
function handleMouseUp(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
isDown=false;
}
function handleMouseOut(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
isDown=false;
}
function handleMouseMove(e){
if(!isDown){return;}
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
getOffset();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
draw(mouseX,mouseY);
}
//252,254,171
function draw(x,y){
ctx.strokeStyle = 'rgba(0,0,0,'+(0.4+Math.random()*0.2)+')';
ctx.beginPath();
ctx.moveTo(xLast, yLast);
ctx.lineTo(x, y);
ctx.stroke();
// Chalk Effect
var length = Math.round(Math.sqrt(Math.pow(x-xLast,2)+Math.pow(y-yLast,2))/(5/brushDiameter));
var xUnit = (x-xLast)/length;
var yUnit = (y-yLast)/length;
for(var i=0; i<length; i++ ){
var xCurrent = xLast+(i*xUnit);
var yCurrent = yLast+(i*yUnit);
var xRandom = xCurrent+(Math.random()-0.5)*brushDiameter*1.2;
var yRandom = yCurrent+(Math.random()-0.5)*brushDiameter*1.2;
ctx.clearRect( xRandom, yRandom, Math.random()*2+2, Math.random()+1);
}
xLast = x;
yLast = y;
}
function getOffset(){
var BB=canvas.getBoundingClientRect();
offsetX=BB.left;
offsetY=BB.top;
}
body{ background-color:ivory; }
#canvas{border:1px solid red; background:white;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Drag to draw pencil line on the pad</h4>
<canvas id="canvas" width=300 height=300></canvas>

Toggle brush colours html5 canvas

I'm trying to create a drawing board with two different colour brushes. You can select the brush you want by clicking on the appropriate button.
Note: This only needs to work on iOS Safari.
The two brushes are:
A Yellow Highlighter
A solid brush colour
The issue I am facing is that selecting a different brush, alters the colour of the existing brush strokes on the canvas.
How can I have each brush not affect the other?
Code:
var el = document.getElementById('c');
var ctx = el.getContext('2d');
var isDrawing;
var _highlight = false;
function marker(){
ctx.lineWidth = 10;
ctx.strokeStyle = 'rgba(0,0,0,1)';
}
function highlight(){
ctx.lineWidth = 15;
ctx.strokeStyle = 'rgba(255,255,0,0.4)';
ctx.globalCompositeOperation = 'destination-atop';
}
document.getElementById("marker").addEventListener("click", function(){
_highlight = false;
});
document.getElementById("clear").addEventListener("click", function(){
ctx.clearRect(0, 0, el.width, el.height);
ctx.restore();
ctx.beginPath();
});
document.getElementById("highlight").addEventListener("click", function(){
_highlight = true;
});
el.onmousedown = function(e) {
isDrawing = true;
if(_highlight){
highlight();
ctx.lineJoin = ctx.lineCap = 'round';
ctx.moveTo(e.clientX, e.clientY);
}else{
marker();
ctx.lineJoin = ctx.lineCap = 'round';
ctx.moveTo(e.clientX, e.clientY);
}
};
el.onmousemove = function(e) {
if (isDrawing) {
if(_highlight){
highlight();
ctx.lineTo(e.clientX, e.clientY);
ctx.stroke();
}else{
marker();
ctx.lineTo(e.clientX, e.clientY);
ctx.stroke();
}
}
};
el.onmouseup = function() {
isDrawing = false;
};
canvas#c {
border: 1px solid #ccc;
background:url(http://i.imgur.com/yf6d9SX.jpg);
position: relative;
left: 0;
top: 0;
z-index: 2;
}
<canvas id="c" width="930" height="500"></canvas>
<br>
<button id="marker">Marker</button>
<button id="highlight">Highlight</button>
<button id="clear">Clear</button>
You are accumulating all lines to the same path, so every time you stroke the current stroke color will be used for all of them, including the previous lines.
Try adding beginPath() at your mouse down event as well as in your pen change.
There are several other issues though in this code not addressed here, including:
Composite mode when pen changes
Mouse positions must be corrected to relative position of canvas
(For marker effect you can also use the new blending mode "multiply" instead of "destination-atop", does not work in IE though).
var el = document.getElementById('c');
var ctx = el.getContext('2d');
var isDrawing;
var _highlight = false;
function marker() {
ctx.lineWidth = 10;
ctx.strokeStyle = 'rgba(0,0,0,1)';
ctx.globalCompositeOperation = 'source-over';
}
function highlight() {
ctx.lineWidth = 15;
ctx.strokeStyle = 'rgba(255,255,0,0.4)';
ctx.globalCompositeOperation = "multiply";
if (ctx.globalCompositeOperation !== "multiply") // use multiply if available
ctx.globalCompositeOperation = 'destination-over'; // fallback mode
}
document.getElementById("marker").addEventListener("click", function() {
_highlight = false;
});
document.getElementById("clear").addEventListener("click", function() {
ctx.clearRect(0, 0, el.width, el.height);
ctx.beginPath();
});
document.getElementById("highlight").addEventListener("click", function() {
_highlight = true;
});
el.onmousedown = function(e) {
var pos = getMouse(e);
isDrawing = true;
ctx.beginPath();
_highlight ? highlight() : marker();
ctx.lineJoin = ctx.lineCap = 'round';
ctx.moveTo(pos.x, pos.y);
};
el.onmousemove = function(e) {
if (isDrawing) {
var pos = getMouse(e);
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
}
};
el.onmouseup = function() {
isDrawing = false;
};
function getMouse(e) {
var rect = el.getBoundingClientRect();
return {x: e.clientX - rect.left, y: e.clientY - rect.top}
}
canvas#c {
border: 1px solid #ccc;
background: url(http://i.imgur.com/yf6d9SX.jpg);
position: relative;
left: 0;
top: 0;
z-index: 2;
}
<canvas id="c" width="930" height="500"></canvas>
<br>
<button id="marker">Marker</button>
<button id="highlight">Highlight</button>
<button id="clear">Clear</button>

Why can I not create a element of canvas with createElement?

I want to create the canvas internally and then just use it normally in my javascript. The following code creates the canvas.
Question: I should be able to create a canvas with the document.createElement("sketchpad")?
var canvas = document.createElement("sketchpad");
Code:
function init()
{
//canvas = document.getElementById('sketchpad');
var canvas = document.createElement("sketchpad");
//var ctx = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 500;
document.body.appendChild(canvas);
if (canvas.getContext)
{
ctx = canvas.getContext('2d');
}
if (ctx)
{
canvas.addEventListener('mousedown', sketchpad_mouseDown, false);
canvas.addEventListener('mousemove', sketchpad_mouseMove, false);
window.addEventListener('mouseup', sketchpad_mouseUp, false);
}
}
All the code below:
<html>
<head>
<title>Sketchpad</title>
<script type="text/javascript">
var canvas;
var ctx;
var mouseX = 0;
var mouseY = 0;
var mouseDown = 0;
function drawDot(ctx,x,y,size)
{
r=0;
g=0;
b=0;
a=256;
ctx.beginPath();
ctx.arc(x, y, size, 0, Math.PI*2, true);
ctx.closePath();
ctx.fillStyle = "rgba("+r+","+g+","+b+","+(a/255)+")";
ctx.fill();
}
function clearCanvas(canvas,ctx)
{
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function sketchpad_mouseDown()
{
mouseDown=1;
drawDot(ctx,mouseX,mouseY,4);
}
function sketchpad_mouseUp()
{
mouseDown=0;
}
function sketchpad_mouseMove(e)
{
getMousePos(e);
if (mouseDown==1)
{
drawDot(ctx,mouseX,mouseY,4);
}
}
function getMousePos(e)
{
if (!e)
{
var e = event;
}
if (e.offsetX)
{
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else if (e.layerX)
{
mouseX = e.layerX;
mouseY = e.layerY;
}
}
function init()
{
//canvas = document.getElementById('sketchpad');
var canvas = document.createElement("sketchpad");
//var ctx = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 500;
document.body.appendChild(canvas);
if (canvas.getContext)
{
ctx = canvas.getContext('2d');
}
if (ctx)
{
canvas.addEventListener('mousedown', sketchpad_mouseDown, false);
canvas.addEventListener('mousemove', sketchpad_mouseMove, false);
window.addEventListener('mouseup', sketchpad_mouseUp, false);
}
}
</script>
<style>
.leftside
{
float:left;
width:120px;
height:25px;
background-color:#def;
padding:10px;
border-radius:4px;
}
.rightside
{
float:left;
margin-left:10px;
}
#sketchpad
{
float:left;
border:4px solid #888;
border-radius:4px;
position:relative;
}
</style>
</head>
<body onload="init()">
<div class="leftside">
<input type="submit" value="Clear Sketchpad" onclick="clearCanvas(canvas,ctx);">
</div>
<div class="rightside">
<!-- <canvas id="sketchpad" height="500" width="500">-->
</canvas>
</div>
</body>
</html>
This new code did not work:
This new code does not work, this is how a person has to create the canvas correct.
var canvas = document.createElement("canvas"); //or what ever name that I want
canvas.id = "sketchpad";
The if statement is not necessary, is it?
function init()
{
//canvas = document.getElementById('sketchpad');
var canvas = document.createElement("canvas");
canvas.id = "sketchpad";
if (canvas.getContext)
{
ctx = canvas.getContext('2d');
}
if (ctx)
{
canvas.addEventListener('mousedown', sketchpad_mouseDown, false);
canvas.addEventListener('mousemove', sketchpad_mouseMove, false);
window.addEventListener('mouseup', sketchpad_mouseUp, false);
}
}
Code here: This code does not seem to work either. I appended the sketchpad to the canvas but it still is not adding it to the document.
function init()
{
//canvas = document.getElementById('sketchpad');
var canvas = document.createElement("canvas");
canvas.id = "sketchpad";
document.getElementById('sketchpad').appendChild(canvas);
if (canvas.getContext)
{
ctx = canvas.getContext('2d');
}
if (ctx)
{
canvas.addEventListener('mousedown', sketchpad_mouseDown, false);
canvas.addEventListener('mousemove', sketchpad_mouseMove, false);
window.addEventListener('mouseup', sketchpad_mouseUp, false);
}
}
sketchpad is not a valid DOM element so it will create a HTMLUnknownElement. This is not what you are looking for.
You want to create a canvas, so lets just create a canvas:
var canvas = document.createElement("canvas");
And give it the ID "sketchpad" if you want:
canvas.id = "sketchpad";
Once you canvas is created, you will need to append it to an existing element of your HTML if you want it to be shown. Ex. if you want your canvas to appear in a div that looks like this:
<div id="rightside" class="rightside">
You would append your canvas like this:
document.getElementById('rightside').appendChild(canvas);
Here is a jsFiddle using your code!
Thats it!
--
Additional source for createElement

Categories

Resources