I am trying to turn a simple drawing on a canvas to a base64 url but when I call toDataURL I get an empty string!
The code is below:
var canvas, context, canvasImage;
var cursorPosition = {
x: undefined,
y: undefined
};
var mouse;
var color = "rgb(0, 123, 255)";
var size = 10;
function throttle(ms, fn) {
var lastCallTime;
return function() {
var now = Date.now();
if (!lastCallTime || now - lastCallTime > ms) {
lastCallTime = now;
fn.apply(this, arguments);
}
};
}
function drawCircle(event) {
context.beginPath();
context.arc(cursorPosition.x, cursorPosition.y, size, 0, 2 * Math.PI);
context.closePath();
context.fillStyle = color;
context.fill();
canvasImage = context.getImageData(
0,
0,
window.innerWidth,
window.innerHeight
);
console.log(canvas.toDataURL());
}
window.onload = function() {
socket.emit("ai");
load("left");
canvas = document.getElementById("number");
canvas.width = 140;
canvas.height = 140;
context = canvas.getContext("2d");
context.fillStyle = "white";
context.fillRect(0, 0, canvas.width, canvas.height);
window.onmousedown = function() {
mouse = "down";
console.log("hi");
};
window.onmouseup = function() {
mouse = "";
};
window.onmousemove = throttle(0.00000000001, function(evt) {
if (mouse == "down") {
var rect = canvas.getBoundingClientRect(), // abs. size of element
scaleX = canvas.width / rect.width, // relationship bitmap vs. element for X
scaleY = canvas.height / rect.height; // relationship bitmap vs. element for Y
cursorPosition = {
x: (evt.clientX - rect.left) * scaleX, // scale mouse coordinates after they have
y: (evt.clientY - rect.top) * scaleY // been adjusted to be relative to element
};
drawCircle(event);
}
});
window.ontouchmove = throttle(10, function(event) {
var rect = canvas.getBoundingClientRect(), // abs. size of element
scaleX = canvas.width / rect.width, // relationship bitmap vs. element for X
scaleY = canvas.height / rect.height; // relationship bitmap vs. element for Y
cursorPosition = {
x: (evt.clientX - rect.left) * scaleX, // scale mouse coordinates after they have
y: (evt.clientY - rect.top) * scaleY // been adjusted to be relative to element
};
console.log(cursorPosition);
drawCircle(event);
});
};
I am able to draw on the canvas but when I call it in the console or in the code I get and empty string like this: ""
Any help would be much appreciated. I've tried a lot of things online but nothing helps.
Related
I'm trying to make a section on a website have two background images that will reveal the bottom one as the pointer moves across the screen.
I'm still new to javascript, and my code is made up of bits and pieces that I've found on google, but I can't seem to get the top image to share the same resolution and image size for whatever reason as the bottom image.
Here is the link to my codepen: https://codepen.io/Awktopus/pen/zYwKOKO
And here is my code:
HTML:
<canvas id="main-canvas" id="canvas-size" class="background-size"></canvas>
<image src="https://i.imgur.com/PbGAAIy.jpg" id="upper-image" class="hidden-bg"></img>
<image src="https://i.imgur.com/Gx14sKW.jpg" id="lower-image" class="hidden-bg"></img>
CSS:
.hidden-bg {
display: none;
}
JS:
var can = document.getElementById('main-canvas');
var ctx = can.getContext('2d');
can.width = window.innerWidth;
can.height = window.innerWidth / 2;
var upperImg = document.getElementById("upper-image");
var lowerImg = document.getElementById("lower-image");
var pat = ctx.createPattern(upperImg, "no-repeat");
var canvas = ctx.canvas ;
var hRatio = canvas.width / lowerImg.width ;
var vRatio = canvas.height / lowerImg.height ;
var ratio = Math.max ( hRatio, vRatio );
var centerShift_x = ( canvas.width - lowerImg.width*ratio ) / 2;
var centerShift_y = ( canvas.height - lowerImg.height*ratio ) / 2;
can.addEventListener('mousemove', function(e) {
var mouse = getMouse(e, can);
redraw(mouse);
}, false);
function redraw(mouse) {
can.width = can.width;
ctx.clearRect(0,0,canvas.width, canvas.height);
ctx.drawImage(lowerImg, 0,0, lowerImg.width, lowerImg.height, centerShift_x,centerShift_y,lowerImg.width*ratio, lowerImg.height*ratio);
ctx.beginPath();
ctx.rect(0,0,can.width,can.height);
ctx.arc(mouse.x, mouse.y, 250, 0, Math.PI*2, true)
ctx.clip();
ctx.fillStyle = pat;
ctx.fillRect(0, 0, lowerImg.width, lowerImg.height, centerShift_x, centerShift_y, lowerImg.width*ratio, lowerImg.height*ratio);
}
var img = new Image();
img.onload = function() {
redraw({x: -500, y:-500})
}
function getMouse(e, canvas) {
var element = canvas,
offsetX = 0,
offsetY = 0,
mx, my;
if (element.offsetParent !== undefined) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
mx = e.pageX - offsetX;
my = e.pageY - offsetY;
return {
x: mx,
y: my
};
}
If I understood this right you will want to set the width and height and draw the upper image using drawImage(). Just use the same ratios as the lowerImage. No need to use createPattern for this.
codepen: https://codepen.io/jfirestorm44/pen/BaRLoxX
var can = document.getElementById('main-canvas');
var ctx = can.getContext('2d');
can.width = window.innerWidth;
can.height = window.innerWidth / 2;
var upperImg = document.getElementById("upper-image");
var lowerImg = document.getElementById("lower-image");
//var pat = ctx.createPattern(upperImg, "no-repeat");
var canvas = ctx.canvas ;
var hRatio = canvas.width / lowerImg.width ;
var vRatio = canvas.height / lowerImg.height ;
var ratio = Math.max ( hRatio, vRatio );
var centerShift_x = ( canvas.width - lowerImg.width*ratio ) / 2;
var centerShift_y = ( canvas.height - lowerImg.height*ratio ) / 2;
can.addEventListener('mousemove', function(e) {
var mouse = getMouse(e, can);
redraw(mouse);
}, false);
function redraw(mouse) {
can.width = can.width;
ctx.clearRect(0,0,canvas.width, canvas.height);
ctx.drawImage(lowerImg, 0,0, lowerImg.width, lowerImg.height, centerShift_x,centerShift_y,lowerImg.width*ratio, lowerImg.height*ratio);
ctx.beginPath();
ctx.rect(0,0,can.width,can.height);
ctx.arc(mouse.x, mouse.y, 250, 0, Math.PI*2, true)
ctx.clip();
ctx.drawImage(upperImg, 0,0, lowerImg.width, lowerImg.height, centerShift_x,centerShift_y,lowerImg.width*ratio, lowerImg.height*ratio);
}
var img = new Image();
img.onload = function() {
redraw({x: -500, y:-500})
}
function getMouse(e, canvas) {
var element = canvas,
offsetX = 0,
offsetY = 0,
mx, my;
if (element.offsetParent !== undefined) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
mx = e.pageX - offsetX;
my = e.pageY - offsetY;
return {
x: mx,
y: my
};
}
.hidden-bg {
display: none;
}
<canvas id="main-canvas" id="canvas-size" class="background-size"></canvas>
<image src="https://i.imgur.com/PbGAAIy.jpg" id="upper-image" class="hidden-bg"></img>
<image src="https://i.imgur.com/Gx14sKW.jpg" id="lower-image" class="hidden-bg"></img>
I'm building a basic game using plain javascript and I am trying to rotate my object to follow my mouse.
I've tried getting the client's mouse X and Y then subtracting the canvas width and height divided by two. Then taking those values and inputing it into Math.atan2(). However, I feel the issue may be in my transform and rotate. The code bellow is what I've tried.
WIDTH = c.height;
HEIGHT = c.width;
document.onmousemove = function(ve){
let cX = -c.width / 2;
let cY = -c.height / 2;
let x = ve.offsetX;
let y = ve.offsetY;
var rX = cX + x - 8;
var rY = cY + y - 8;
player.angle = Math.atan2(rX, rY) / Math.PI * 180;
}
function update(){
var now = Date.now();
dt = now - lastUpdate;
ctx.clearRect(0, 0, WIDTH, HEIGHT);
ctx.setTransform(1, 0, 0, 1, WIDTH / 2, HEIGHT / 2);
ctx.rotate(player.angle + 10);
drawCircle(player.x, player.y, 20, 0, 180, "red");
tx.setTransform(1, 0, 0, 1, 0, 0);
}
setInterval(update, dt/10000);
The player spins around my mouse in wide circles with no apparent pattern.
Here's a gif showing what's happening.
https://gyazo.com/006c99879ecf219791d059de14d98b74
In order to rotate the object to follow the mouse you need to get the angle between the previous position of the mouse and the actual position of the mouse and use this angle to rotate the object. Also the object is drawn with the tip in the origin of the canvas {x:0,y:0} so you'll need to translate the player to the position of the mouse.
I hope this is what you need.
const ctx = c.getContext("2d")
const HEIGHT = c.height = window.innerHeight;
const WIDTH = c.width = window.innerWidth;
let m = {x:0,y:0}
let prev = {x:0,y:0}
let angle = 0;
c.addEventListener("mousemove",(evt)=>{
ctx.clearRect(-WIDTH, -HEIGHT, 2*WIDTH, 2*HEIGHT);
// the previous position of the mouse
prev.x = m.x;
prev.y = m.y;
//the actual position of the mouse
m = oMousePos(c, evt);
// if the mpuse is moving get the angle between the previoue position and the actual position of the mouse
if(m.x != prev.x && m.y != prev.y){
angle = Math.atan2(m.y-prev.y, m.x-prev.x)
}
ctx.restore();
ctx.save();
ctx.translate(m.x, m.y);
ctx.rotate(angle);
drawPlayer();
})
function drawPlayer(){
ctx.fillStyle = "black";
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(-20,-5);
ctx.lineTo(-20,5);
ctx.lineTo(0,0);
ctx.closePath();
ctx.fill()
}
// a function to detect the mouse position
function oMousePos(canvas, evt) {
var ClientRect = canvas.getBoundingClientRect();
return { //objeto
x: Math.round(evt.clientX - ClientRect.left),
y: Math.round(evt.clientY - ClientRect.top)
}
}
<canvas id="c"></canvas>
As an observation: in your code you have Math.atan2(rX, rY) The first argument has to be y.
So I've recently been messing around with html5 canvas and trying to figure out how to make a particle system. While it does work I want to make vx = mouse coordinates(specifically x) but they start from the center.
What I mean by this is basically if the cursor is in the center of the canvas then vx would be equal to 0 and if the cursor is to the right from the center of the canvas it have positive mouse coordinates (and if the cursor is to the left from the center of canvas it have negative mouse coordinates).
Once that is accomplished I would just do p.speed += p.vx
Here is my javascript:
window.onload = function(){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var W = window.innerWidth, H = window.innerHeight;
canvas.width = W;
canvas.height = H;
var particles = [];
var particle_count = 100;
for(var i = 0; i < particle_count; i++)
{
particles.push(new particle());
}
function particle()
{
this.vx = -1 + Math.random() * 2;
this.speed = {x: 0, y: -15+Math.random()*10};
this.location = {x: W/2, y: H/2};
this.radius = 5+Math.random()*10;
this.life = 20+Math.random()*10;
this.remaining_life = this.life;
this.r = Math.round(Math.random()*255);
this.g = Math.round(Math.random()*55);
this.b = Math.round(Math.random()*5);
}
function draw()
{
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = "black";
ctx.fillRect(0, 0, W, H);
ctx.globalCompositeOperation = "lighter";
for(var i = 0; i < particles.length; i++)
{
var p = particles[i];
ctx.beginPath();
p.opacity = Math.round(p.remaining_life/p.life*100)/100
var gradient = ctx.createRadialGradient(
p.location.x, p.location.y, 0, p.location.x, p.location.y, p.radius);
gradient.addColorStop(0, "rgba("+p.r+", "+p.g+", "+p.b+", "+p.opacity+")");
gradient.addColorStop(0.5, "rgba("+p.r+", "+p.g+", "+p.b+", "+p.opacity+")");
gradient.addColorStop(1, "rgba("+p.r+", "+p.g+", "+p.b+", 0)");
ctx.fillStyle = gradient;
ctx.arc(p.location.x, p.location.y, p.radius, Math.PI*2, false);
ctx.fill();
p.remaining_life--;
p.radius--;
p.location.x += p.speed.x += p.vx;
p.location.y += p.speed.y;
if(p.remaining_life < 0 || p.radius < 0) {
particles[i] = new particle();
}
}
}
setInterval(draw, 33); }
Here is my codepen.
You need to translate context to move origin to center.
You also need to reverse the translation on the mouse coordinates as they will still be relative to the upper-left corner (assuming the coordinates are corrected to be relative to canvas).
Example:
var cx = canvas.width * 0.5;
var cy = canvas.height * 0.5;
ctx.translate(cx, cy); // translate globally once
For each mouse coordinate compensate with the translated position:
var pos = getMousePosition(evt); // see below
var x = pos.x - cx;
var y = pos.y - cy;
To adjust mouse position:
function getMousePosition(evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
}
}
I'm trying to make a scratch card using canvas with JS. my question is:
can I know if the user have "erased" all the canvas?
I have two images one on top the other, and I managed to make the user "erase" the on-top canvas image. I want to fire up a function when the canvas is empty\completly erased.
Thanks
var offsetT;
var offsetL;
var canvas = document.createElement('canvas');
canvas.id = "canvas";
var canvasWidth = 290;
var canvasheight = 269;
canvas.width = canvasWidth;
canvas.height = canvasheight;
var context = canvas.getContext("2d");
var scratcher = document.getElementById("scratcher");
var radius = 20; //Brush Radius
context.drawImage(scratcher,0,0);
// set image as pattern for fillStyle
context.globalCompositeOperation = 'destination-out';
context.fillStyle = context.createPattern(scratcher, "repeat");
// for demo only, reveals image while mousing over canvas
canvas.onmousemove = function (e) {
var r = this.getBoundingClientRect(),
x = e.clientX - r.left,
y = e.clientY - r.top;
context.beginPath();
context.moveTo(x + radius, y);
context.arc(x, y, radius, 0, 2 * Math.PI);
context.fill();
};
document.body.appendChild(canvas);
document.addEventListener('touchmove', function(e){
var touchobj = e.changedTouches[0]; // reference first touch point (ie: first finger)
var x = touchobj.clientX;
var y = touchobj.clientY;
offsetT = canvas.offsetTop;
offsetL = canvas.offsetLeft;
context.beginPath();
context.moveTo(x-offsetL + radius, y-offsetT);
context.arc(x-offsetL,y-offsetT, radius, 0, 2 * Math.PI);
context.fill();
var cursor = document.getElementById('cursor');
cursor.style.display = 'block';
cursor.style.left = x+ "px";
cursor.style.top = y+ "px";
e.preventDefault();
}, false);
The only way is to check the imageData of the canvas :
var data = ctx.getImageData(0,0,ctx.canvas.width, ctx.canvas.height).data;
var isEmpty = !Array.prototype.some.call(data, function(p){return p>0;});
var ctx = c.getContext('2d');
var isEmpty = function(ctx){
var data = ctx.getImageData(0,0,ctx.canvas.width, ctx.canvas.height).data;
return !Array.prototype.some.call(data, function(p){return p>0;});
}
//first check before drawing
log.innerHTML += isEmpty(ctx)+' ';
//no more empty
ctx.fillRect(0,0,10,10);
// recheck
log.innerHTML += isEmpty(ctx);
/*
we could also have used a for loop :
//in Function
for(var i=0; i<data.length; i++){
if(data[i]>0){
return false;
}
return true;
}
*/
<canvas id="c"></canvas>
<p id="log"></p>
http://jsfiddle.net/cs5Sg/11/
I want to do the scalable canvas. I created two circles (arcs) and one line, when you click on circle and move it, the line will follow and change position. The problem is when I added code for resize:
var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d'),
radius = 12,
p = null,
point = {
p1: { x:100, y:250 },
p2: { x:400, y:100 }
},
moving = false;
window.addEventListener("resize", OnResizeCalled, false);
function OnResizeCalled() {
var gameWidth = window.innerWidth;
var gameHeight = window.innerHeight;
var scaleToFitX = gameWidth / 800;
var scaleToFitY = gameHeight / 480;
var currentScreenRatio = gameWidth / gameHeight;
var optimalRatio = Math.min(scaleToFitX, scaleToFitY);
if (currentScreenRatio >= 1.77 && currentScreenRatio <= 1.79) {
canvas.style.width = gameWidth + "px";
canvas.style.height = gameHeight + "px";
}
else {
canvas.style.width = 800 * optimalRatio + "px";
canvas.style.height = 480 * optimalRatio + "px";
}
}
function init() {
return setInterval(draw, 10);
}
canvas.addEventListener('mousedown', function(e) {
for (p in point) {
var
mouseX = e.clientX - 1,
mouseY = e.clientY - 1,
distance = Math.sqrt(Math.pow(mouseX - point[p].x, 2) + Math.pow(mouseY - point[p].y, 2));
if (distance <= radius) {
moving = p;
break;
}
}
});
canvas.addEventListener('mouseup', function(e) {
moving = false;
});
canvas.addEventListener('mousemove', function(e) {
if(moving) {
point[moving].x = e.clientX - 1;
point[moving].y = e.clientY - 1;
}
});
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(point.p1.x,point.p1.y);
context.lineTo(point.p2.x,point.p2.y);
context.closePath();
context.fillStyle = '#8ED6FF';
context.fill();
context.stroke();
for (p in point) {
context.beginPath();
context.arc(point[p].x,point[p].y,radius,0,2*Math.PI);
context.fillStyle = 'red';
context.fill();
context.stroke();
}
context.closePath();
}
init();
The canvas is scalable, but the problem is with the points (circles). When you change the window size, they still have the same position on the canvas area, but the distance change (so the click option fails). How to fix that?
Live Demo
Basically you just need a scaler value that takes into account the actual dimensions of the canvas, and the css dimensions like so
var scaledX = canvas.width/ canvas.offsetWidth,
scaledY = canvas.height/ canvas.offsetHeight;
And then every time the window is resized you need to make sure to update the scaler values.
function OnResizeCalled() {
scaledX = canvas.width/ canvas.offsetWidth;
scaledY = canvas.height/ canvas.offsetHeight;
}
To get the correct coords you need to multiply the clientX and clientY by the scaler in all of your mouse events
canvas.addEventListener('mousedown', function(e) {
for (p in point) {
var
mouseX = e.clientX*scaledX,
mouseY = e.clientY*scaledY,
distance = Math.sqrt(Math.pow(mouseX - point[p].x, 2) + Math.pow(mouseY - point[p].y, 2));
if (distance <= radius) {
moving = p;
break;
}
}
});
canvas.addEventListener('mousemove', function(e) {
var mouseX = e.clientX*scaledX,
mouseY = e.clientY*scaledY;
if(moving) {
point[moving].x = mouseX;
point[moving].y = mouseY;
}
});
Full code
var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d'),
radius = 12,
p = null,
point = {
p1: { x:100, y:250},
p2: { x:400, y:100}
},
moving = false,
scaledX = canvas.width/ canvas.offsetWidth,
scaledY = canvas.height/ canvas.offsetHeight;
window.addEventListener("resize", OnResizeCalled, false);
function OnResizeCalled() {
var gameWidth = window.innerWidth;
var gameHeight = window.innerHeight;
var scaleToFitX = gameWidth / 800;
var scaleToFitY = gameHeight / 480;
var currentScreenRatio = gameWidth / gameHeight;
var optimalRatio = Math.min(scaleToFitX, scaleToFitY);
if (currentScreenRatio >= 1.77 && currentScreenRatio <= 1.79) {
canvas.style.width = gameWidth + "px";
canvas.style.height = gameHeight + "px";
}
else {
canvas.style.width = 800 * optimalRatio + "px";
canvas.style.height = 480 * optimalRatio + "px";
}
scaledX = canvas.width/ canvas.offsetWidth;
scaledY = canvas.height/ canvas.offsetHeight;
}
function init() {
return setInterval(draw, 10);
}
canvas.addEventListener('mousedown', function(e) {
for (p in point) {
var
mouseX = e.clientX*scaledX,
mouseY = e.clientY*scaledY,
distance = Math.sqrt(Math.pow(mouseX - point[p].x, 2) + Math.pow(mouseY - point[p].y, 2));
if (distance <= radius) {
moving = p;
break;
}
}
});
canvas.addEventListener('mouseup', function(e) {
moving = false;
});
canvas.addEventListener('mousemove', function(e) {
var mouseX = e.clientX*scaledX,
mouseY = e.clientY*scaledY;
if(moving) {
point[moving].x = mouseX; //1 is the border of your canvas
point[moving].y = mouseY;
}
});
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(point.p1.x,point.p1.y);
context.lineTo(point.p2.x,point.p2.y);
context.closePath();
context.fillStyle = '#8ED6FF';
context.fill();
context.stroke();
for (p in point) {
context.beginPath();
context.arc(point[p].x,point[p].y,radius,0,2*Math.PI);
context.fillStyle = 'red';
context.fill();
context.stroke();
}
context.closePath();
}
init();