How can I download html5 canvas drawing as image - javascript

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>

Related

Why is my cursor and my line of draw are in diffrent sides?

I am attempting to create a drawing app in JS, however, whenever anything is drawn, it is positioned away from my cursor depending on where it is on the canvas, when I am on the furthest left/bottom side of the canvas, you can draw where your cursor is, but the further right/up I move, the more the brush begins to "drift" and go further than where my cursor is.
const canvas = document.getElementById("canvas");
const increaseBtn = document.getElementById("increase");
const decreaseBtn = document.getElementById("decrease");
const sizeEl = document.getElementById("size");
const colorEl = document.getElementById("color");
const clearEl = document.getElementById("clear");
//Core Drawing Functionality (with some research)
const ctx = canvas.getContext("2d");
let size = 5;
let isPressed = false;
let color = "black";
let x;
let y;
let fakeSize = 1;
canvas.addEventListener("mousedown", (e) => {
isPressed = true;
x = e.offsetX;
y = e.offsetY;
});
canvas.addEventListener("mouseup", (e) => {
isPressed = false;
x = undefined;
y = undefined;
});
canvas.addEventListener("mousemove", (e) => {
if (isPressed) {
const x2 = e.offsetX;
const y2 = e.offsetY;
drawCircle(x2, y2);
drawLine(x, y, x2, y2);
x = x2;
y = y2;
}
});
function drawCircle(x, y) {
ctx.beginPath();
ctx.arc(x, y, size, 0, Math.PI * 2);
ctx.fillStyle = color;
ctx.fill();
}
function drawLine(x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.strokeStyle = color;
ctx.lineWidth = size * 2;
ctx.stroke();
}
function updateSizeOnScreen() {
sizeEl.innerHTML = fakeSize;
}
increaseBtn.addEventListener("click", () => {
size += 5;
fakeSize++;
if (fakeSize > 10) {
fakeSize = 10;
}
if (size > 50) {
size = 50;
}
updateSizeOnScreen();
});
decreaseBtn.addEventListener("click", () => {
size -= 5;
fakeSize--;
if (fakeSize < 1) {
fakeSize = 1;
}
if (size < 5) {
size = 5;
}
updateSizeOnScreen();
});
colorEl.addEventListener("change", (e) => {
color = e.target.value;
});
clearEl.addEventListener("click", () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
//Eraser and Pencil Actions (my own algorithm)
const eraser = document.getElementById("eraser");
const pencil = document.getElementById("pencil");
eraser.addEventListener("click", () => {
localStorage.setItem("colorEl", JSON.stringify(color));
color = "#fff";
colorEl.disabled = true;
canvas.classList.add("eraseractive");
eraser.classList.add("eraseractive");
colorEl.classList.add("eraseractive");
canvas.classList.remove("pencilactive");
eraser.classList.remove("pencilactive");
colorEl.classList.remove("pencilactive");
});
pencil.addEventListener("click", () => {
JSON.parse(localStorage.getItem("colorEl"));
color = colorEl.value;
colorEl.disabled = false;
canvas.classList.remove("eraseractive");
eraser.classList.remove("eraseractive");
colorEl.classList.remove("eraseractive");
canvas.classList.add("pencilactive");
eraser.classList.add("pencilactive");
colorEl.classList.add("pencilactive");
});
// Dark/Light Mode
const darkMode = document.getElementById("darkMode");
const lightMode = document.getElementById("lightMode");
const toolbox = document.getElementById("toolbox");
darkMode.addEventListener("click", () => {
darkMode.classList.add("mode-active");
lightMode.classList.remove("mode-active");
lightMode.classList.add("rotate");
darkMode.classList.remove("rotate");
toolbox.style.backgroundColor = "#293462";
document.body.style.backgroundImage =
"url('/assets/images/darkModeBackground.svg')";
document.body.style.backgroundSize = "1920px 1080px";
canvas.style.borderColor = "#293462";
toolbox.style.borderColor = "#293462";
});
lightMode.addEventListener("click", () => {
lightMode.classList.add("mode-active");
darkMode.classList.remove("mode-active");
darkMode.classList.add("rotate");
lightMode.classList.remove("rotate");
toolbox.style.backgroundColor = "#293462";
document.body.style.backgroundImage =
"url('/assets/images/lightModeBackground.svg')";
document.body.style.backgroundSize = "1920px 1080px";
canvas.style.borderColor = "#293462";
toolbox.style.borderColor = "#293462";
});
* {
box-sizing: border-box;
font-size: 20px !important;
}
body {
background: url("https://drawing-app-green.vercel.app/assets/images/lightModeBackground.svg");
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
margin: 0;
position: relative;
max-height: 100vh;
overflow: hidden;
}
::selection {
background: transparent;
}
::-moz-selection {
background: transparent;
}
.mode {
display: flex;
position: absolute;
top: 10px;
right: 25px;
cursor: pointer;
}
.light-mode {
color: yellow;
}
.dark-mode {
color: #16213e;
}
.container {
display: flex;
flex-direction: column;
max-width: 1200px;
width: 100%;
max-height: 600px;
height: 100%;
}
canvas {
display: flex;
border: 2px solid #293462;
cursor: url("https://drawing-app-green.vercel.app/assets/images/pencilCursor.png") 2 48, pointer;
background-color: #fff;
margin-top: 3rem;
width: 100%;
height: 600px;
}
.toolbox {
background-color: #293462;
border: 1px solid #293462;
display: flex;
width: 100%;
align-items: center;
justify-content: center;
padding: 0.2rem;
}
.toolbox > * {
background-color: #fff;
border: none;
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 2rem;
height: 30px;
width: 30px;
margin: 0.25rem;
padding: 0.25rem;
cursor: pointer;
}
.toolbox > *:last-child {
margin-left: auto;
}
canvas.eraseractive {
cursor: url("https://drawing-app-green.vercel.app/assets/images/eraserCursor.png") 2 48, pointer;
}
#color.eraseractive {
cursor: not-allowed;
}
canvas.pencilactive {
cursor: url("https://drawing-app-green.vercel.app/assets/images/pencilCursor.png") 2 48, pointer;
}
.mode-active {
visibility: hidden;
}
.rotate {
transform: rotate(360deg);
transition: transform 1s linear;
}
<!DOCTYPE html>
<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" />
<title>Drawing App</title>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"
integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
</head>
<body>
<i class="fa-solid fa-moon dark-mode fa-2x mode" id="darkMode"></i>
<i
class="fa-solid fa-sun light-mode fa-2x mode mode-active"
id="lightMode"
></i>
<div class="container">
<canvas id="canvas" width="1024" height="600"></canvas>
<div class="toolbox" id="toolbox">
<button id="decrease">-</button>
<span id="size">1</span>
<button id="increase">+</button>
<input type="color" id="color" />
<button id="pencil">
<img src="assets/images/pencilCursor.png" alt="" />
</button>
<button id="eraser">
<img src="assets/images/eraserCursor.png" alt="" />
</button>
<button id="clear">X</button>
</div>
</div>
<script src="assets/js/script.js"></script>
</body>
</html>
Your problem is that your canvas dimentions don't match with the dimentions of the HTML element that contains it. You see: your canvas has a fixed width="" and height="" attributes set. But in your HTML your canvas element has a width of 100%. So that means that the container vairies in dimentions but the canvas inside it not. This result in the canvas trying to resize to show inside the container thus giving you issues with calculating exacly what pixel you are clicking.
You have two options:
Option 1: calculate your click position taking into account canvas deformation
If you want your canvas to resize, then calculate the real position using a simple ratio formula. If for example your canvas has a width of 100 but right now its container is 10px wide, then if you click on pixel 5 you expect a dot to be drawn at pixel 50. In other words if your canvas is smaller by a factor of 10 then you need to multiply your position by a factor of 10.
In your code it would look something like this:
// this is your same code in lines 33 ana34 but see that I added a multiplication by the ratio between the canvas size and the canvas container
const x2 = e.offsetX * (canvas.width / ctx.canvas.getBoundingClientRect().width);
const y2 = e.offsetY * (canvas.height / ctx.canvas.getBoundingClientRect().height);
Option #2: Dont allow your canvas to deform
Remove the container class, and remove the width:100% from your canvas css. Your canvas will overflow and cause a scrollbar but the positions will be calculated properly with your code.

How can I draw JavaScript graphical elements on top of custom image?

I have some Javascript drawing random square elements in the DOM. I have a gif (Image) I want these elements to appear over but they keep appearing underneath the gif. I tried defining z-depth and layout parameters to move these elements on top of the image here, but this produced no difference.
Any assistance in achieving the result (drawing elements onclick, on top of this gif) would be much appreciated.
I ultimately want to draw various other images over this image onclick, restricted to this particular area on top of the gif. If someone can suggest a solution to this as well I would be very much grateful!
(Code features some unused elements from my past attempts)
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="div.css" />
</head>
<body>
<div style="cursor: pointer;" id="boxy" >
<img src="bg.gif" alt="unfinished bingo card" onclick="create()" />
</div>
</div>
<script>
var body = document.getElementsByTagName("body")[0];
var canvas = document.createElement("canvas");
canvas.height = 1300;
canvas.width = 1300;
var context = canvas.getContext("2d");
body.appendChild(canvas);
var rects = [];
function create() {
// Opacity
context.globalAlpha = 0.7;
var color = '#' + Math.round(0xffffff * Math.random()).toString(16);
context.fillStyle = color;
//Each rectangle's size is (20 ~ 100, 20 ~ 100)
var coordx = Math.random() * canvas.width;
var coordy = Math.random() * canvas.width;
var width = Math.random() * 80 + 20;
var height = Math.random() * 80 + 20;
var rect = {
x: coordx,
y: coordy,
w: width,
h: height
}
var ok = true;
rects.forEach(function (item) {
if (isCollide(rect, item)) {
console.log("collide");
ok = false;
} else {
console.log("no collision");
}
})
if (ok) {
context.fillRect(coordx, coordy, width, height);
rects.push(rect);
} else {
console.log('rect dropped');
}
console.log(rects);
}
function isCollide(a, b) {
return !(
((a.y + a.h) < (b.y)) ||
(a.y > (b.y + b.h)) ||
((a.x + a.w) < b.x) ||
(a.x > (b.x + b.w))
);
}
document.getElementById('boxy').addEventListener('click', create);
document.getElementById('canvas').style.position = "relative";
document.getElementById('canvas').style.zIndex = "10";
</script>
</body>
</html>
#my-div {
width: 1300x;
height: 1300px;
z-index: -1;
}
a.fill-div {
display: block;
height: 100%;
width: 100%;
text-decoration: none;
}
#boxy {
display: inline-block;
height: 100%;
width: 100%;
text-decoration: none;
z-index: -1;
}
.canvas {
display: inline-block;
height: 100%;
width: 100%;
text-decoration: none;
z-index: 10;
}
You have to use position:absolute; to take it out of the html flow.
Now anything added after the image will be placed like the image was never there.
img {
width: 100vw;
height: 100vh;
position: absolute;
top: 0;
left: 0;
z-index: -10;
}
div {
font-size: 2rem;
color: white;
}
<img src="https://images.unsplash.com/photo-1664273107076-b6d1fbfb973b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1171&q=80">
<div>Hello i am on top of the image
</div>

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>

multiple canvas as buttons with onclick event

I'm having really big problems with canvas code that I'm using only 1 time in the page (in logo) working fine, and that I'm trying to use it as buttons for menu and here is the problem, I don't know really what's im doing wrong, hope some of u help me.
it's the code that I'm using for the logo and is working fine:
HTML CODE:
<html>
<head>
<title>canvas</title>
</head>
<body>
<div id="container">
<div id="logo">
<canvas style="" width="800" id="broken-glass"></canvas>
<h1 style="color: rgba(250, 250, 250, 0.95);" id="logo-title">Canvas</h1>
</div>
<script type="text/javascript">
(function() {
var isCanvasSupported = function () {
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
};
if( isCanvasSupported() ) {
var canvas = document.getElementById('broken-glass'),
context = canvas.getContext('2d'),
width = canvas.width = Math.min(800, window.innerWidth),
height = canvas.height,
numTriangles = 100,
rand = function(min, max){
return Math.floor( (Math.random() * (max - min + 1) ) + min);
};
window.drawTriangles = function(){
context.clearRect(0, 0, width, height);
var hue = rand(0,360);
var increment = 80 / numTriangles;
for(var i = 0; i < numTriangles; i++) {
context.beginPath();
context.moveTo(rand(0,width), rand(0,height) );
context.lineTo(rand(0,width), rand(0,height) );
context.lineTo(rand(0,width), rand(0,height) );
context.globalAlpha = 0.5;
context.fillStyle = 'hsl('+Math.round(hue)+', '+rand(15,60)+'%, '+ rand(10, 60) +'%)';
context.closePath();
context.fill();
hue+=increment;
if(hue > 360) hue = 0;
}
canvas.style.cssText = '-webkit-filter: contrast(115%);';
};
document.getElementById('logo-title').style.color = 'rgba(250, 250, 250, 0.95)';
drawTriangles();
var el = document.getElementById('logo');
el.onclick = function() {
drawTriangles();
};
}
})();
</script>
</div>
</body>
</html>
and it's CSS CODE:
#broken-glass
{
position: absolute;
left: 0px;
top: 0px;
width: 100%;
}
#logo h1
{
text-align: center;
font-weight: 700;
width: 100%;
color: #000;
position: absolute;
left: 0px;
-moz-user-select: none;
cursor: pointer;
margin-top: 27px;
font-size: 63px;
line-height: 1.4;
top: 0px;
margin-bottom: 5px;
text-rendering: optimizelegibility;
font-family: Calibri,"PT Sans","Trebuchet MS","Helvetica Neue",Arial;
}
the big problem comes when i change the id's (#) to classes (.) and the "id" tag to "class" tag in the html, the canvas is overlapped... the text of h1 tag is out of the canvas... and just the hell of problems, can someone tell me what I'm doing wrong?, how to fix it, I'm trying it during hours...
too much thanks in advance!.
you may try putting an !important in every code in your css.
example:
text-align: center !important;
font-weight: 700 !important;
this fixed my problem before, hopefully it will fix yours also.

DOM Exception 18 while Detecting pixel color on a canvas

I am trying to finish HTML5/javascript game and testing it in crome.
Whever i am pointing over the image for detecting pixel color There an error display in console.
Unable to get image data from canvas because the canvas has been tainted by cross-origin data. e001-4.html:27
Uncaught Error: SecurityError: DOM Exception 18
Please tell me what is it and what'wrong in the code.
Here is the code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Canvas Example 4 (Detecting Colors)</title>
<script>
window.onload = function () {
var preview = document.getElementById('preview');
var r = document.getElementById('r');
var g = document.getElementById('g');
var b = document.getElementById('b');
var a = document.getElementById('a');
var mx = document.getElementById('mx');
var my = document.getElementById('my');
var canvas = document.getElementById('myCanvas');
canvas.addEventListener('mousemove', move, false);
var c = canvas.getContext('2d');
var building = new Image()
building.src = "img/sprite1.png";
draw();
function draw () {
c.drawImage(building, 0, 0, canvas.width, canvas.height);
}
function move (e) {
mx.innerHTML = e.clientX;
my.innerHTML = e.clientY;
var img = c.getImageData(e.clientX, e.clientY, 1, 1);
var idata = img.data;
var red = idata[0];
var green = idata[1];
var blue = idata[2];
var alpha = idata[3];
r.innerHTML = red;
g.innerHTML = green;
b.innerHTML = blue;
a.innerHTML = (alpha > 0) ? alpha : 'Transparent';
var rgba='rgba(' + red + ', ' + green + ', ' + blue + ', ' + alpha + ')';
preview.style.backgroundColor =rgba;
}
}
</script>
<style type="text/css" media="screen">
body { margin: 0px; padding: 0px; }
canvas {
border: 1px solid black;
float: left;
}
ul {
list-style: none;
margin: 10px 10px 10px 10px;
padding: 0px;
float: left;
}
ul li { font-weight: bold; }
ul li span { font-weight: normal; }
ul li #preview { width: 50px; height: 50px; border: 1px solid black; }
</style>
</head>
<body>
<canvas id="myCanvas" width="300" height="300">
Your browser doesn't include support for the canvas tag.
</canvas>
<ul>
<li><div id="preview"></div></li>
<li>Red: <span id="r">NULL</span></li>
<li>Green: <span id="g">NULL</span></li>
<li>Blue: <span id="b">NULL</span></li>
<li>Alpha: <span id="a">NULL</span></li>
<li>Mouse X: <span id="mx">NULL</span></li>
<li>Mouse Y: <span id="my">NULL</span></li>
</ul>
</body>
</html>
A local web server is a very useful development tool.
But, if you just want to test images while satisfying CORS requirements then check out dropbox.com.
If you sign up and put your images in your public folder, then you can satisfy CORS restrictions by applying building.crossOrigin="anonymous";
Try to use a local Web server and serve the page from it.
Example use apache and put the file in htdoc folder and look for the result.

Categories

Resources