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

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

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>

How to upload image to canvas and draw squares on it and get the squares' coordinates

I'm trying to upload an image to canvas and draw squares on it and get the squares' coordinates to send it to the backend for keys identification.
But something not right, I can't draw squares on my images.
This is my javascript which I use:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var rect = {};
var drag = false;
var imageObj = null;
function init() {
imageObj = new Image();
imageObj.onload = function () { ctx.drawImage(imageObj, 0, 0); };
imageObj.src =
canvas.addEventListener('mousedown', mouseDown, false);
canvas.addEventListener('mouseup', mouseUp, false);
canvas.addEventListener('mousemove', mouseMove, false);
}
function mouseDown(e) {
rect.startX = e.pageX - this.offsetLeft;
rect.startY = e.pageY - this.offsetTop;
drag = true;
}
function mouseUp() { drag = false; }
function mouseMove(e) {
if (drag) {
ctx.clearRect(0, 0, 500, 500);
ctx.drawImage(imageObj, 0, 0);
rect.w = (e.pageX - this.offsetLeft) - rect.startX;
rect.h = (e.pageY - this.offsetTop) - rect.startY;
ctx.strokeStyle = 'red';
ctx.strokeRect(rect.startX, rect.startY, rect.w, rect.h);
}
}
//
init();
</script>
<script type="text/javascript">
document.getElementById('imageLoader').onchange = function(e) {
var img = new Image();
img.onload = draw;
img.onerror = failed;
img.src = URL.createObjectURL(this.files[0]);
};
function draw() {
var canvas = document.getElementById('canvas');
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0,0);
}
function failed() {
console.error("The provided file couldn't be loaded as an Image media");
}
and HTML:
<canvas id="canvas" ></canvas>
<input type="file" id="imageLoader" name="imageLoader"/>
You just need to assign the image to imageObj.
function draw() {
canvas.width = this.width;
canvas.height = this.height;
ctx.drawImage(this, 0,0);
imageObj = this; //here
}
JSFiddle here

Add Clear button to canvas

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>

fill-in image with canvas drawing

code description:
i am using canvas to draw using some java-script .. i am expecting the user to draw some thing in the canvas area then save it or clean the canvas area ..
this is what i have done so far .. here is the code/; but it needs a browser to work
https://jsfiddle.net/RababAlkhalifa/k0y1yzh8/
java script:
var lastPt = null;
var canvas;
var ctx;
function init() {
canvas = document.getElementById("mycanvas");
ctx = canvas.getContext("2d");
var offset = getOffset(canvas);
if (window.PointerEvent) {
canvas.addEventListener("pointerdown", function() {
canvas.addEventListener("pointermove", draw, false);
}, false);
canvas.addEventListener("pointerup", endPointer, false);
} else {
//Provide fallback for user agents that do not support Pointer Events
canvas.addEventListener("mousedown", function() {
canvas.addEventListener("mousemove", draw, false);
}, false);
canvas.addEventListener("mouseup", endPointer, false);
}
}
// Event handler called for each pointerdown event:
function draw(e) {
if (lastPt != null) {
ctx.beginPath();
// Start at previous point
ctx.moveTo(lastPt.x, lastPt.y);
// Line to latest point
ctx.lineTo(e.pageX, e.pageY);
// Draw it!
ctx.stroke();
}
//Store latest pointer
lastPt = { x: e.pageX, y: e.pageY };
}
function getOffset(obj) {
//...
}
function endPointer(e) {
//Stop tracking the pointermove (and mousemove) events
canvas.removeEventListener("pointermove", draw, false);
canvas.removeEventListener("mousemove", draw, false);
//Set last point to null to end our pointer path
lastPt = null;
}
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
var w = canvas.width;
canvas.width = 1;
canvas.width = w;
}
function download() {
var dt = canvas.toDataURL();
this.href = dt; //this may not work in the future..
clearCanvas();
}
document.getElementById('download').addEventListener('click', download, false);
html:
<canvas id="mycanvas" width="600px" height="600px" style="border:1px solid black;"></canvas>
<div class="convas_contrllers">
<button onclick="clearCanvas()">Clear</button>
<a id="download" download="CanvasDemo.png">Download as image</a>
</div>
<a id="download" download="CanvasDemo.png">Download as image</a>
<div class="slide" id="img1"><img src="http://placehold.it/300x100&text=FooBar1" /></div>
the problem:
i need to put the saved canvas in the image id=img1 element before clear or saving the canvas .. is this possible ?
Yes, this is possible. Here's how you could achieve that ...
var image = document.querySelector('#img1');
var canvas = document.querySelector('#mycanvas');
var ctx = canvas.getContext('2d');
var isMousePressed = false;
canvas.onmousedown = function(e) {
isMousePressed = true;
ctx.beginPath();
ctx.moveTo(e.offsetX, e.offsetY);
};
canvas.onmouseup = function() {
isMousePressed = false;
};
canvas.onmousemove = function(e) {
if (isMousePressed) {
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
}
};
function clearCanvas() {
image.src = canvas.toDataURL();
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function download() {
image.src = canvas.toDataURL();
var a = document.createElement('a');
a.href = canvas.toDataURL();
a.download = 'myImage.png'; //image name
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
body{margin:10px 0 0 0;overflow:hidden}.slide{position:absolute;top:10px;left:200px}
<canvas id="mycanvas" width="180" height="180" style="border:1px solid black; cursor: default;"></canvas>
<div class="convas_contrllers">
<button id="clear" onclick="clearCanvas()">Clear</button>
<button id="download" onclick="download()">Download as image</button>
</div>
<div class="slide"><img id="img1" src="https://placehold.it/300x100&text=FooBar1"></div>

drawing a rectange over an image on canvas using dragging event

I am trying to draw a rectangle on an image using the mouse and dragging events on HTML5.
My code is shown below. When I draw the rectangle below, the actual image on the canvas disappears. Could you tell me what I am doing wrong? My intended goal is to have the rectangle on top of the image. I have attached a picture of what I actually want to see as the end result.
What am I doing wrong ?
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="400"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
ctx.drawImage(imageObj, 69, 50);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
// ctx.globalAlpha = 0.5;
rect = {},
drag = false;
var rectStartXArray = new Array() ;
var rectStartYArray = new Array() ;
var rectWArray = new Array() ;
var rectHArray = new Array() ;
function init() {
canvas.addEventListener('mousedown', mouseDown, false);
canvas.addEventListener('mouseup', mouseUp, false);
canvas.addEventListener('mousemove', mouseMove, false);
}
function mouseDown(e) {
rect.startX = e.pageX - this.offsetLeft;
rect.startY = e.pageY - this.offsetTop;
drag = true;
}
function mouseUp() {
rectStartXArray[rectStartXArray.length] = rect.startX;
rectStartYArray[rectStartYArray.length] = rect.startY;
rectWArray[rectWArray.length] = rect.w;
rectHArray[rectHArray.length] = rect.h;
drag = false;
}
function mouseMove(e) {
if (drag) {
rect.w = (e.pageX - this.offsetLeft) - rect.startX;
rect.h = (e.pageY - this.offsetTop) - rect.startY;
ctx.clearRect(0, 0, canvas.width, canvas.height);
draw();
}
//drawOldShapes();
}
function draw() {
ctx.beginPath();
ctx.fillStyle="#FF0000";
ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
ctx.stroke();
}
function drawOldShapes(){
for(var i=0;i<rectStartXArray.length;i++)
{
if(rectStartXArray[i]!= rect.startX && rectStartYArray[i] != rect.startY && rectWArray[i] != rect.w && rectHArray[i] != rect.h)
{
ctx.beginPath();
ctx.fillStyle="#FF0000";
ctx.fillRect(rectStartXArray[i], rectStartYArray[i], rectWArray[i], rectHArray[i]);
ctx.stroke();
}
}
}
init();
</script>
</body>
</html>
You are clearing the whole canvas inside draw() by calling ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);. Remove the line and it works. Fiddle - http://jsfiddle.net/da8wv75k/

Categories

Resources