Canvas rendered under div instead of over the div - javascript

On my website, I want do render a <canvas> on top of a <div> with some other <div>'s in it. This is all working okay, however, drawing in the canvas is not possible, because it's positioned under the main <div>. You can test it in the codepen below. You can only draw on a small strip near the bottom.
Codepen: http://codepen.io/anon/pen/hfmBG
Code:
<html>
<head>
<script type="text/javascript">
var canvas, ctx, flag = false,
prevX = 0,
currX = 0,
prevY = 0,
currY = 0,
dot_flag = false;
var x = "#000",
y = 1;
function init() {
canvas = document.getElementById('can');
ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
canvas.addEventListener("mousemove", function (e) {
findxy('move', e)
}, false);
canvas.addEventListener("mousedown", function (e) {
findxy('down', e)
}, false);
canvas.addEventListener("mouseup", function (e) {
findxy('up', e)
}, false);
canvas.addEventListener("mouseout", function (e) {
findxy('out', e)
}, false);
}
function draw() {
ctx.beginPath();
ctx.moveTo(prevX, prevY);
ctx.lineTo(currX, currY);
ctx.strokeStyle = x;
ctx.lineWidth = y;
ctx.stroke();
ctx.closePath();
}
function erase() {
var m = confirm("Want to clear");
if (m) {
ctx.clearRect(0, 0, w, h);
document.getElementById("canvasimg").style.display = "none";
}
}
function findxy(res, e) {
if (res == 'down') {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
flag = true;
dot_flag = true;
if (dot_flag) {
ctx.beginPath();
ctx.fillStyle = x;
ctx.fillRect(currX, currY, 2, 2);
ctx.closePath();
dot_flag = false;
}
}
if (res == 'up' || res == "out") {
flag = false;
}
if (res == 'move') {
if (flag) {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
draw();
}
}
}
function print(){
var c = document.getElementById("can");
var ctx = c.getContext("2d");
var imgData = ctx.getImageData(10,10,50,50);
console.log(imgData);
}
</script>
<style>
.patternlockbutton{
border-color: red;
background-color: transparent;
background-repeat:no-repeat;
display:block;
width:33px;
height:33px;
float:left;
margin:26px;
z-index:1;
-ms-touch-action: none;
border-style: solid;
border-width: 5px;
-webkit-border-top-left-radius: 50px;
-webkit-border-top-right-radius: 50px;
-moz-border-radius-topleft: 50px;
-moz-border-radius-topright: 50px;
border-top-left-radius: 50px;
border-top-right-radius: 50px;
-webkit-border-bottom-left-radius: 50px;
-webkit-border-bottom-right-radius: 50px;
-moz-border-radius-bottomleft: 50px;
-moz-border-radius-bottomright: 50px;
border-bottom-left-radius: 50px;
border-bottom-right-radius: 50px;
}
#can {
z-index: 99;
display: block;
}
</style>
</head>
<body onload="init()">
<div style="width:300px;height:400px;">
<div class="patternlockbutton" id="patternlockbutton1"></div>
<div class="patternlockbutton" id="patternlockbutton2"></div>
<div class="patternlockbutton" id="patternlockbutton3"></div>
<div class="patternlockbutton" id="patternlockbutton4"></div>
<div class="patternlockbutton" id="patternlockbutton5"></div>
<div class="patternlockbutton" id="patternlockbutton6"></div>
<div class="patternlockbutton" id="patternlockbutton7"></div>
<div class="patternlockbutton" id="patternlockbutton8"></div>
<div class="patternlockbutton" id="patternlockbutton9"></div>
<canvas id="can" width="300px" height="400px"></canvas>
</div>
<input type="button" value="clear" id="clr" size="23" onclick="erase()" style="position:absolute;top:55%;left:15%;">
<button onclick="print()">Console.log</button>
</body>
</html>

If you want to position an HTML element on top of other elements, you should set its position: absolute in CSS.
In your case, the parent div of the canvas should have this style applied:
position: relative;
The canvas should have this style applied:
position: absolute;
top: 0;
left: 0;

Related

How do I create another line without the previous deleting - Canvas - JavasScript - HTML5 - CSS

const canvas = document.getElementById('drawing-board');
const toolbar = document.getElementById('toolbar');
const ctx = canvas.getContext('2d');
const canvasOffsetX = canvas.offsetLeft;
const canvasOffsetY = canvas.offsetTop;
canvas.width = window.innerWidth - canvasOffsetX;
canvas.height = window.innerHeight - canvasOffsetY;
let isPainting = false;
let lineWidth = 5;
let startX;
let startY;
toolbar.addEventListener('click', e => {
if (e.target.id === 'clear') {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
});
toolbar.addEventListener('change', e => {
if(e.target.id === 'stroke') {
ctx.strokeStyle = e.target.value;
}
if(e.target.id === 'lineWidth') {
lineWidth = e.target.value;
}
});
const draw = (e) => {
if(!isPainting) {
return;
}
ctx.lineWidth = lineWidth;
ctx.lineCap = 'round';
ctx.lineTo(e.clientX - canvasOffsetX, e.clientY);
ctx.stroke();
}
canvas.addEventListener('mousedown', (e) => {
isPainting = true;
startX = e.clientX;
startY = e.clientY;
});
canvas.addEventListener('mouseup', e => {
isPainting = false;
ctx.stroke();
ctx.beginPath();
});
canvas.addEventListener('mousemove', draw);
body {
margin: 0;
padding: 0;
height: 100%;
overflow: hidden;
color: white;
}
h1 {
background: #7F7FD5;
background: -webkit-linear-gradient(to right, #91EAE4, #86A8E7, #7F7FD5);
background: linear-gradient(to right, #91EAE4, #86A8E7, #7F7FD5);
background-clip: text;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.container {
height: 100%;
display: flex;
}
#toolbar {
display: flex;
flex-direction: column;
padding: 5px;
width: 70px;
background-color: #202020;
}
#toolbar * {
margin-bottom: 6px;
}
#toolbar label {
font-size: 12px;
}
#toolbar input {
width: 100%;
}
#toolbar button {
background-color: #1565c0;
border: none;
border-radius: 4px;
color:white;
padding: 2px;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Drawing app</title>
</head>
<body>
<section class="container">
<div id="toolbar">
<h1>Draw.</h1>
<label for="stroke">Stroke</label>
<input id="stroke" name='stroke' type="color">
<label for="lineWidth">Line Width</label>
<input id="lineWidth" name='lineWidth' type="number" value="5">
<button id="clear">Clear</button>
</div>
<div class="drawing-board">
<canvas id="drawing-board"></canvas>
</div>
</section>
<script src="./index.js"></script>
</body>
</html>
I am making a simple line drawer and this is what I have so far. One of the main features i need it to have is solid straight lines as this is for a bigger project in which this is meant to represent pipes. So the lines cannot bend or curve but must be how the code shows it to be. The issue i am having now is if i want to have the lines to stay on the canvas after another mouse down and click then the lines aren't straight and is almost a paint application. I have provided the code down below.
const canvasEle = document.getElementById('drawContainer');
const context = canvasEle.getContext('2d');
let startPosition = {x: 0, y: 0};
let lineCoordinates = {x: 0, y: 0};
let isDrawStart = false;
const getClientOffset = (event) => {
const {pageX, pageY} = event.touches ? event.touches[0] : event;
const x = pageX - canvasEle.offsetLeft;
const y = pageY - canvasEle.offsetTop;
return {
x,
y
}
}
const drawLine = () => {
if(!isDrawStart) {
return;
}
context.beginPath();
context.moveTo(startPosition.x, startPosition.y);
context.lineTo(lineCoordinates.x, lineCoordinates.y);
context.stroke();
}
const mouseDownListener = (event) => {
startPosition = getClientOffset(event);
isDrawStart = true;
}
const mouseMoveListener = (event) => {
if(!isDrawStart) return;
lineCoordinates = getClientOffset(event);
clearCanvas();
drawLine();
}
const mouseupListener = (event) => {
isDrawStart = false;
}
const clearCanvas = () => {
context.clearRect(0, 0, canvasEle.width, canvasEle.height);
}
canvasEle.addEventListener('mousedown', mouseDownListener);
canvasEle.addEventListener('mousemove', mouseMoveListener);
canvasEle.addEventListener('mouseup', mouseupListener);
canvasEle.addEventListener('touchstart', mouseDownListener);
canvasEle.addEventListener('touchmove', mouseMoveListener);
canvasEle.addEventListener('touchend', mouseupListener);
body {
margin: 0;
padding: 0;
height: 100%;
overflow: hidden;
color: white;
}
h1 {
background: #7F7FD5;
background: -webkit-linear-gradient(to right, #91EAE4, #86A8E7, #7F7FD5);
background: linear-gradient(to right, #91EAE4, #86A8E7, #7F7FD5);
background-clip: text;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.container {
height: 100%;
display: flex;
}
#toolbar {
display: flex;
flex-direction: column;
padding: 5px;
width: 70px;
background-color: #202020;
}
#toolbar * {
margin-bottom: 6px;
}
#toolbar label {
font-size: 12px;
}
#toolbar input {
width: 100%;
}
#toolbar button {
background-color: #1565c0;
border: none;
border-radius: 4px;
color:white;
padding: 2px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<canvas id = "drawContainer" width = "500" height = "500" style = "border: 1px solid #333;"></canvas>
<script src="index.js"></script>
</body>
</html>
Adding line segments
I am guessing this is what you are after. A set of line segments added as the use clicks and drags (mouse or touch)
The simplest solution is to create an array of lines, adding lines to the array at the end of each click drag interaction.
Example
The example adds some functions to create points and lines, draw a line and lines from an array of lines.
const ctx = canvas.getContext('2d'), lines = [];
const Point = (x = 0, y = 0) => ({x,y});
const Line = (p1, p2) => ({p1, p2});
var currentLine = Line(Point(), Point()), addingLine = false;
["mousedown", "mousemove", "mouseup", "touchstart", "touchmove", "touchend"].forEach(name => canvas.addEventListener(name, mouseEvent));
function getClientOffset(event, point) {
event = event.touches ? event.touches[0] : event;
point.x = event.pageX - canvas.offsetLeft;
point.y = event.pageY - canvas.offsetTop;
}
function drawLine(line) {
ctx.moveTo(line.p1.x, line.p1.y);
ctx.lineTo(line.p2.x, line.p2.y);
}
function UpdateDisplay() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
for (const l of lines) { drawLine(l) }
addingLine && drawLine(currentLine);
ctx.stroke();
}
function mouseEvent(event) {
if (event.type === "mousedown" || event.type === "touchstart") {
getClientOffset(event, currentLine.p1);
getClientOffset(event, currentLine.p2);
addingLine = true;
UpdateDisplay();
} else if (event.type === "mouseup" || event.type === "touchend") {
lines.push(currentLine);
currentLine = Line(Point(), Point());
addingLine = false;
UpdateDisplay();
} else if(addingLine) {
getClientOffset(event, currentLine.p2);
UpdateDisplay();
}
}
<canvas id = "canvas" width = "500" height = "500" style = "border: 1px solid #333;"></canvas>

How can I download html5 canvas drawing as image

I just recently uploaded my code files to a server. My website is a simple html5 drawing application where users are able to draw freely. I have this part done fine, however I am looking to implement a download button that simply downloads whatever the user has drawn as an image directly to their device i.e. phone, table, desktop. I have been looking for solutions to this for hours now and cant find anything. Is it a problem with my server? or anything like that? any help would be much appreciated. Below is my code
<!DOCTYPE html>
<html>
<head>
<title>Elemental</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
#import url('https://fonts.googleapis.com/css?family=Montserrat+Alternates');
#media screen and (max-width: 425px){
html,body{
overflow-x: hidden;
width: 100%;
margin: 0;
}
canvas { border: 3px solid #0BF446;
border-radius: 15px 0px 15px 0px;
display: block;
margin: 0 auto;
margin-top: 35px;
background-color:#313131;
position: relative;}
#download{background-color:#04A12B ;
border-radius: 0 15px 0 15px;
padding: 20px 40px;
margin: 0 auto;
display: block;
font-size: 14px;
margin-top: 35px;
color: white;
font-family: 'Montserrat Alternates', sans-serif;}
#clearbutton{background-color:#04A12B ;
border-radius: 0 15px 0 15px;
padding: 20px;
margin: 0 auto;
display: block;
font-size: 14px;
color: white;
font-family: 'Montserrat Alternates', sans-serif;
margin-top: 35px;}
</style>
</head>
<body>
<body onload="init()">
<img src="minilogo.png" id ="logo">
<canvas id="c" width="350px" height="350px"></canvas>
<button id = "download">Download</button>
<input type = "submit" value="Clear Sketchpad" id="clearbutton" onclick="clearCanvas(canvas,ctx);">
<script>
function init() {
// Get the specific canvas element from the HTML document
canvas = document.getElementById('c');
}
function midPointBtw(p1, p2) {
return {
x: p1.x + (p2.x - p1.x) / 2,
y: p1.y + (p2.y - p1.y) / 2
};
}
function getPattern() {
return ctx.createPattern(img, 'repeat');
}
var el = document.getElementById('c');
var ctx = el.getContext('2d');
ctx.lineWidth = 30;
ctx.lineJoin = ctx.lineCap = 'round';
var img = new Image;
img.onload = function() {
ctx.strokeStyle = getPattern();
};
img.src = "https://i.postimg.cc/rF2R0GRY/dick2.png";
var isDrawing, points = [];
var getXY = function(e) {
var source = e.touches ? e.touches[0] : e;
return {
x: source.clientX,
y: source.clientY
};
};
var startDrawing = function(e) {
isDrawing = true;
points.push(getXY(e));
event.preventDefault();
};
var keepDrawing = function(e) {
if (!isDrawing) return;
points.push(getXY(e));
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
var p1 = points[0];
var p2 = points[1];
ctx.moveTo(p1.x, p1.y);
for (var i = 1, len = points.length; i < len; i++) {
var midPoint = midPointBtw(p1, p2);
ctx.quadraticCurveTo(p1.x, p1.y, midPoint.x, midPoint.y);
p1 = points[i];
p2 = points[i + 1];
}
ctx.lineTo(p1.x, p1.y);
ctx.stroke();
event.preventDefault();
};
var stopDrawing = function() {
isDrawing = false;
points = [];
};
el.addEventListener('touchstart', startDrawing);
el.addEventListener('mousedown', startDrawing);
el.addEventListener('touchmove', keepDrawing);
el.addEventListener('mousemove', keepDrawing);
el.addEventListener('touchend', stopDrawing);
el.addEventListener('mouseup', stopDrawing);
function clearCanvas(canvas,ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath()
}
</script>
</body>
</html>
You can use the Canvas#toDataURL method to generate a URL containing all the data of the canvas's current image. This can then be used in place of any URL -- a link's href, a window.open, etc. For a download link, you can use the download attribute on a link, which is an HTML5 addition. The value of the download attribute is the filename that will be used as the default save filename.
So to put all that together:
<a id='downloadLink' download='myDrawing.png'>Download Image</a>
<script>
function createDownload() {
const downloadURL = document.getElementById('c').toDataURL();
document.getElementById('downloadLink').href = downloadURL;
}
</script>

Cursor position not good

I looked for solutions to this problem for a long time, found some and I thought I understand but apparently I don't. I'd like to make a canvas that ppl can use to sign to confirm a booking. But I can't get the line to follow the user's cursor. My code looks like this:
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Signature Test</title>
<link rel="stylesheet" href="../css/test.css">
<script src="../js/jquery-3.2.0.js"></script>
</head>
<body>
<header id="header">
</header>
<section id="content">
<canvas id="signaturePad">DSorry your browser is rubbish</canvas>
</section>
<footer>
</footer>
<script src="../js/test.js"></script>
</body>
</html>
CSS:
body
{
margin: 0;
padding: 0;
}
header
{
border: 1px solid black;
width: 100%;
height: 50px;
}
#content
{
border: 1px solid blue;
width: 100%;
height: 300px;
position: relative;
}
#content #signaturePad
{
border: 1px solid red;
width: 200px;
height: 200px;
position: absolute;
left: calc(50% - 100px);
top: calc(50% - 100px);
}
footer
{
border: 1px solid black;
width: 100%;
height: 50px;
}
And finally the JS:
var canvas = document.getElementById("signaturePad");
var context = canvas.getContext("2d");
var radius = 1;
var dragging = false;
context.lineWidth = 2*radius;
function displayMousePosition(mouseX, mouseY) {
var header = document.getElementById("header");
header.innerHTML = "X : " + mouseX + "<br />Y : " + mouseY;
}
function getMousePosition(e) {
var mouseX = 0,
mouseY = 0,
elmX = 0,
elmY = 0,
obj = this;
//get mouse position on document crossbrowser
if (!e){e = window.event;}
if (e.pageX || e.pageY){
mouseX= e.pageX;
mouseY = e.pageY;
} else if (e.clientX || e.clientY){
mouseX = e.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
mouseY = e.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
//get parent element position in document
if (obj.offsetParent){
do{
elmX += obj.offsetLeft;
elmY += obj.offsetTop;
} while (obj = obj.offsetParent);
}
displayMousePosition(mouseX, mouseY);
return [mouseX, mouseY];
}
var putPoint = function(e) {
if(dragging) {
var offset = $("#signaturePad").offset();
var mouseX = getMousePosition(e)[0];
var mouseY = getMousePosition(e)[1];
context.lineTo(mouseX, mouseY);
context.stroke();
context.beginPath();
context.arc(mouseX, mouseY, radius, 0, Math.PI*2);
context.fill();
context.beginPath();
context.moveTo(mouseX, mouseY);
}
}
$(document).on("mousedown", "#signaturePad", function(e) {
dragging = true;
putPoint(e);
});
$(document).on("mouseup", "#signaturePad", function() {
dragging = false;
context.beginPath();
});
$(document).on("mousemove", "#signaturePad", function(e) {
putPoint(e);
});
And the fiddle if you wanna see it live: https://jsfiddle.net/Cellendhyll/yxguemf0/7/

Reverse image at end of animation

I'm trying to re-create the bouncing ball effect but with an arrow.
When the arrow gets to the right wall it points left and come back until it reach the left wall and then point right again. Within a continuous loop.
I'm fairly new to JS and animation. Any help would be appreciated.
So far I have the arrow work fine back and forth, but doesn't reverse/flip when hitting the wall.
Thank you.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<canvas id="canvas" width="500" height="400" style="border: solid; border-color: black;"></canvas>
<script type="text/javascript">
window.onload = function () {
var context;
var dx = 1;
var w3;
var ctx;
var img;
function setCanvas() {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
ctx = canvas.getContext('2d');
img = new Image();
img.onload = function (e) {
draw();
}
img.src = '/rightArrow2.png';
w3 = img.width;
draw();
}
}
var startPos = 200;
var endPos = 100;
var x = 100;
var y = 10;
function draw() {
ctx.clearRect(0, 0, 500, 500);
ctx.drawImage(img, x, y);
x += dx;
if (x < endPos || x > startPos) {
ctx.clearRect(0, 0, 500, 500);
var canvas = document.getElementById('canvas');
ctx2 = canvas.getContext('2d');
var img2 = new Image();
img2.src = document.getElementById("canvas").toDataURL();
var w4 = img2.width;
ctx2.save();
ctx2.translate(-w4, 0);
ctx2.scale(-1, 1);
ctx2.drawImage(img2, x , y);
ctx2.restore();
dx = -dx;
}
setTimeout(draw, 15);
}
setCanvas();
}
</script>
</body>
</html>
var context;
var dx= 4;
var dy=4;
var y=150;
var x=10;
function draw(){
context= myCanvas.getContext('2d');
context.clearRect(0,0,300,300);
context.beginPath();
context.fillStyle="#0000ff";
context.arc(x,y,20,0,Math.PI*2,true);
context.closePath();
context.fill();
if( x<0 || x>300)
dx=-dx;
if( y<0 || y>300)
dy=-dy;
x+=dx;
y+=dy;
}
setInterval(draw,10);
<!--
body { background-color:#ededed; font:normal 12px/18px Arial, Helvetica, sans-serif; }
#container { width:600px; margin:0 auto; }
#myCanvas { background:#fff; border:1px solid #cbcbcb; }
#nav { display:block; width:100%; text-align:center; }
#nav li { display:block; font-weight:bold; line-height:21px; text-shadow:1px 1px 1px #fff; width:100px; height:21px; padding:5px; margin:0 10px; background:#e0e0e0; border:1px solid #ccc; -moz-border-radius:4px;-webkit-border-radius:4px; border-radius:4px; float:left; }
#nav li a { color:#000; display:block; text-decoration:none; width:100%; height:100%; }
-->
<div id="container">
<canvas id="myCanvas" width="300" height="300"></canvas>
<ul id="nav">
<li>View Tutorial</li>
<li>Post Comment</li>
</ul>
</div>
Try replacing your draw() function with this:
function draw() {
ctx.clearRect(0, 0, 500, 500);
if (dx > 0) {
ctx.drawImage(img, x, y);
}
else {
ctx.save();
ctx.translate(x + img.width, y);
ctx.scale(-1, 1);
ctx.drawImage(img, 0, 0);
ctx.restore();
}
x += dx;
if (x < endPos || x > startPos) {
dx = -dx;
}
setTimeout(draw, 15);
}

Chrome Extension Script not Working

I am extremely new to creating extensions for chrome, and right now I'm just trying to mess around and create a simple canvas that you can open up and draw on.
When I load popup.html as a normal webpage everything seems to work just fine, but when I open the extension in chrome there is no functionality.
Manifest:
{
"manifest_version": 2,
"name": "Sketchpad",
"description": " ",
"version": "0.1",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
}
}
HTML:
<!doctype html>
<html>
<head>
<title>Drawing Pad</title>
<style>
body {
font-family: "Segoe UI", "Lucida Grande", Tahoma, sans-serif;
font-size: 100%;
}
.color {display: inline-block;}
#can {
cursor: url(pencil.png), auto;
}
</style>
<script src="canvas.js"></script>
</head>
<body onload="init()">
<canvas id="can" width="400" height="400" style="border:2px solid;"></canvas><br>
<div style="display: inline-block;">Choose Color
<div class="color" style="width: 10px; height: 10px; background: green;" id="green" onclick="color(this)"></div>
<div class="color" style="width: 10px; height: 10px; background: blue;" id="blue" onclick="color(this)"></div>
<div class="color" style="width: 10px; height: 10px; background: red;" id="red" onclick="color(this)"></div>
<div class="color" style="width: 10px; height: 10px; background: yellow;" id="yellow" onclick="color(this)"></div>
<div class="color" style="width: 10px; height: 10px; background: orange;" id="orange" onclick="color(this)"></div>
<div class="color" style="width: 10px; height: 10px; background: black;" id="black" onclick="color(this)"></div>
</div>
<div style="display: inline-block;">Eraser
<div style="width:15px;height:15px;background:white;border:2px solid;display: inline-block" id="white" onclick="color(this)"></div>
</div><br>
<input type="button" value="Clear" id="clr" size="23" onclick="erase()">
</body>
</html>
JS:
var canvas, ctx, flag = false,
prevX = 0,
currX = 0,
prevY = 0,
currY = 0,
dot_flag = false;
var x = "black",
y = 2;
function init() {
canvas = document.getElementById('can');
ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
canvas.addEventListener("mousemove", function (e) {
findxy('move', e)
}, false);
canvas.addEventListener("mousedown", function (e) {
findxy('down', e)
}, false);
canvas.addEventListener("mouseup", function (e) {
findxy('up', e)
}, false);
canvas.addEventListener("mouseout", function (e) {
findxy('out', e)
}, false);
}
function color(obj) {
switch (obj.id) {
case "green":
x = "green";
break;
case "blue":
x = "blue";
break;
case "red":
x = "red";
break;
case "yellow":
x = "yellow";
break;
case "orange":
x = "orange";
break;
case "black":
x = "black";
break;
case "white":
x = "white";
break;
}
if (x == "white") y = 14;
else y = 2;
}
function draw() {
ctx.beginPath();
ctx.moveTo(prevX, prevY);
ctx.lineTo(currX, currY);
ctx.strokeStyle = x;
ctx.lineWidth = y;
ctx.stroke();
ctx.closePath();
}
function erase() {
ctx.clearRect(0, 0, w, h);
}
function findxy(res, e) {
if (res == 'down') {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
flag = true;
dot_flag = true;
if (dot_flag) {
ctx.beginPath();
ctx.fillStyle = x;
ctx.fillRect(currX, currY, 2, 2);
ctx.closePath();
dot_flag = false;
}
}
if (res == 'up' || res == "out") {
flag = false;
}
if (res == 'move') {
if (flag) {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
draw();
}
}
}
After doing some research I have a feeling that something is wrong with the way I have my js code formatted, but I cannot pinpoint what that is. Sorry for the long post and thanks, any help is appreciated.
You can't put javascript code in html file in goolge-chrome-extension.
replace
html
<body onload="init()">
with:
js
document.body.addEventListener('load', function () {...})
For more information, see contentSecurityPolicy.
Also since inline JS is not allowed, onclick like <input type="button" value="Clear" id="clr" size="23" onclick="erase()"> should be
<input type="button" value="Clear" id="clr" size="23"> and use addEventListener to bind the event in your js file.
document.addEventListener('DOMContentLoaded', function() {
var clear = document.getElementById('clr');
clear.addEventListener('click', function() {
erase();
});
});

Categories

Resources