So I am trying to make an image appear as if it is moving across and canvas and restore the previous background when its next drawn.
The following test worked when drawing a basic rectangle.
var canvas = document.querySelector('canvas'),
ctx = canvas.getContext('2d');
var x = 10, = 10, w = 50, h = 50;
var vx = 2;
var vy = 2;
var back = ctx.getImageData(1,1,1,1);
function draw() {
ctx.putImageData(back,x, y);
x += vx;
y += vy;
back=ctx.getImageData(x, y, w, h);
ctx.fillRect(x, y, w, h);
}
setInterval(draw, 1000/60);
However when substituting the rectangle for an image as follows, it doesnt appear to show point.png and instead the imagedata for "back" appears to move.
var canvas = document.querySelector('canvas'),
ctx = canvas.getContext('2d');
var x = 10,
y = 10,
w = 50,
h = 50;
var vx = 2;
var vy = 2;
var back = ctx.getImageData(1, 1, 1, 1);
function draw() {
ctx.putImageData(back, x, y);
x += vx;
y += vy;
back = ctx.getImageData(x, y, w, h);
var img = document.getElementById("point");
ctx.drawImage(img, x, y, w, h);
}
setInterval(draw, 1000 / 60);
Can anyone tell me what I am doing wrong and how to fix this?
check the console, you should see something like that
`Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.`
Once you have inserted some external datas in the the canvas, you can not access to its contents anymore.
The image must have the same origin as the page.
Related
I don't know js, I write on python, but I need to draw circles on web page at the clicked location. So, for really I use selenium and I need to see where the click is. Because I don't click the dom elements, I click coordinates and sometimes Selenium click wrong, so I want to control it.
I tried some code like below, of course it doesn't work, i don't know why. So I found the similar solution. It doesn't work for me. So I can't find the working solution for highlighting the clicks.
var canv = document.createElement('canvas');
canv.id = 'canvas';
document.body.appendChild(canv);
document.getElementById('canvas').appendChild(canv);
onclick = function showCoords(event) {
var x = event.clientX;
var y = event.clientY;
var radius = 5;
var canvas = document.getElementsByTagName('canvas');
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(x, y, radius, 40, 0, 2 * Math.PI);
ctx.stroke();
var coords = 'X coords: ' + x + ', Y coords: ' + y;
console.log(coords);
}
You try to append the canvas to the canvas
This works
var canv = document.createElement('canvas');
canv.id = 'canvas';
document.body.appendChild(canv);
var ctx = canv.getContext('2d');
canv.addEventListener("click",function(event) {
var x = event.clientX;
var y = event.clientY;
var radius = 5;
ctx.beginPath();
ctx.arc(x, y, radius, 40, 0, 2 * Math.PI);
ctx.stroke();
var coords = 'X coords: ' + x + ', Y coords: ' + y;
console.log(coords);
})
The decision is
var myCanvas = document.createElement('canvas');
document.body.appendChild(myCanvas);
myCanvas.id = 'canvas';
myCanvas.style.position = 'absolute';
myCanvas.style.left = "0px";
myCanvas.style.top = "0px";
myCanvas.width = window.innerWidth;
myCanvas.height = window.innerHeight;
var ctx = myCanvas.getContext('2d');
myCanvas.addEventListener("click", function (event) {
var x = event.clientX;
var y = event.clientY;
ctx.fillStyle = "#2980b9";
ctx.beginPath();
ctx.arc(x, y, 10, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath();
setTimeout(function () { ctx.clearRect(0, 0, myCanvas.width, myCanvas.height) }, 300);
})
I want to create a break out game through javascript. I am wondering why the ctx.clearRect does not working. I want to put the rectangle in the y coordinate 430 to make it show at the bottom of the canvas. It moves when I have used the window.setInterval. But the rectangle move continuously.
Any help would be appreciated. Sorry for my poor English.
var canvas = document.getElementById("canvas");
const ctx = canvas.getContext('2d');
var position = 0;
var yposition = 430;
var length = 80;
var width = 20;
var xSpeed = length*1;
var ySpeed = 0;
function R(){
ctx.fillStyle = "green";
ctx.fillRect(position, yposition, length, width);
};
function C(){
position += xSpeed;
yposition += ySpeed;
};
window.setInterval(() => {
ctx.clearRect(0, 430, length, width);
R();
C();
},150);
ctx.beginPath();
ctx.arc(150, 50, 20, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fillStyle = "blue";
ctx.fill();
The culprit are the parameters you're feeding into the clearRect function:
(0, 430, length, width)
Since length and width are hardcoded values of 80 and 20 respectively, the above means every time the intervals callback function gets fired it clears a rectangular area of 80 x 20 pixels at x = 0 and y = 430.
As your green paddle is moving you're actually clearing an area your paddle isn't located at anymore.
So you basically have two options:
Clear the whole canvas every frame
Clear the screen area your paddle has been before changing it's position
The second would look a little something like this:
var canvas = document.getElementById("canvas");
const ctx = canvas.getContext('2d');
var position = 0;
var yposition = 150;
var length = 80;
var width = 20;
var xSpeed = length * 1;
var ySpeed = 0;
function R() {
ctx.fillStyle = "green";
ctx.fillRect(position, yposition, length, width);
}
function C() {
position += xSpeed;
yposition += ySpeed;
}
window.setInterval(() => {
ctx.clearRect(position, yposition, length, width);
C();
R();
}, 500);
<canvas id="canvas" width="600" height="400"></canvas>
I'd definitely recommend clearing the whole canvas though since there will be other on-screen objects beside the paddle.
I am trying to write a code using HTML canvas that will create a line beginning where a mousemove event occurs. The line has a defined direction and should continue extending until it is off the screen. The issue I am having is that every time I move the mouse a new line begins(this is good) but the previous line stops extending. I believe that the issue is because each new line is taking on a set of parameters with the same name as the previous line, however I am not certain that this is the issue, nor do I know how to fix it.
Here is a jsfiddle of my current code: https://jsfiddle.net/tdammon/bf8xdyzL/
I start be creating an object named mouse that takes an x and y parameter. The xbeg and ybeg will be the starting coordinates for my lines.
let canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height= window.innerHeight;
let c = canvas.getContext('2d');
let mouse ={
x:undefined,
y:undefined,
}
window.addEventListener("mousemove",function(event){
mouse.x = event.x;
mouse.y = event.y;
xbeg = mouse.x;
ybeg = mouse.y;
})
Next I create an animate function that continuously calls itself. I create a new line object which will take the xbeg and ybeg parameters for beginning points and xbeg+10 and ybeg+10 as ending point. The function then increments xbeg and ybeg. I would like this function to create new lines that do not stop extending whenever the mouse is moved.
function animate() {
requestAnimationFrame(animate);
new Line(xbeg,ybeg,xbeg+10,ybeg+10)
c.beginPath();
c.moveTo(xbeg,ybeg);
c.lineTo(xbeg+10,ybeg+10);
c.stroke();
xbeg += 1;
ybeg += 1;
}
I've added to your code an array for all your lines: let linesRy = []; and I've changed a bit your draw() function by adding this.endx++; this.endy++;
also I'm using your commented out c.clearRect(0, 0, innerWidth, innerHeight);since with every frame you redraw all the lines.
I hope this is what you need.
let linesRy = [];
let canvas = document.querySelector("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let c = canvas.getContext("2d");
let mouse = {
x: undefined,
y: undefined
};
let xbeg, ybeg;
window.addEventListener("mousemove", function(event) {
mouse.x = event.x;
mouse.y = event.y;
xbeg = mouse.x;
ybeg = mouse.y;
});
class Line {
constructor(begx, begy, endx, endy, dx, dy, slope) {
this.begx = begx;
this.begy = begy;
this.endx = endx;
this.endy = endy;
this.dx = endx - begx;
this.dy = endy - begy;
this.slope = dy / dx;
}
draw() {
this.endx++;
this.endy++;
c.beginPath();
c.moveTo(this.begx, this.begy);
c.lineTo(this.endx, this.endy);
c.stroke();
}
}
//let xend = 420;
//let yend = 220;
function animate() {
requestAnimationFrame(animate);
c.clearRect(0, 0, innerWidth, innerHeight);
linesRy.push(new Line(xbeg, ybeg, xbeg + 10, ybeg + 10, 10, 10, 1));
linesRy.forEach(l => {
l.draw();
});
}
animate();
canvas{border:1px solid;}
<canvas></canvas>
the variable c is taken local variable
function animate() {
c = canvas.getContext('2d');
requestAnimationFrame(animate);
new Line(xbeg,ybeg,xbeg+10,ybeg+10)
c.beginPath();
c.moveTo(xbeg,ybeg);
c.lineTo(xbeg+10,ybeg+10);
c.stroke();
xbeg += 1;
ybeg += 1;
}
I am working on animation optimisation and i wanted to try out canvas to see how it performs but i am not experienced well in canvas and i dont know how to prepare concept of this kind of animation.
this is the gif that shows how animation should rotate like:
this is my current code of js:
var cvs = document.getElementById('coin-spin'),
ctx = cvs.getContext('2d'),
w = cvs.width = 400,
h = cvs.height = 400,
cx = w / 2,
cy = h / 2,
a = 0;
var img = new Image();
var loop = function() {
// BG
ctx.fillStyle = '#ccc';
ctx.fillRect(0, 0, w, h);
// draw image
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(Math.PI / 180 * a);
ctx.translate(-cx, -cy);
ctx.drawImage(img, cx - (img.width / 2), cy - (img.height / 2));
ctx.restore();
// axis
ctx.strokeStyle = '#000';
ctx.beginPath();
ctx.moveTo(cx, 0);
ctx.lineTo(cx, h);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0, cy);
ctx.lineTo(w, cy);
ctx.stroke();
//mod angle
a++;
window.requestAnimationFrame(loop);
};
img.onload = function() {
loop();
};
img.src = 'https://image.ibb.co/gqkeXx/coin.png';
and the working demo on fiddle.
Could someone show how to add to the code so the image would rotate horizontally like on the gif?
EDIT ----
I added the spin, as it was also something to do, but still struggling on how to rotate it.
To get around the problem of rotating the object along two axes (faking one by mapping width to a sine wave), you can use an offscreen canvas to render the coin rotating around one axis, then render that canvas applying the second rotation ;
//make an offscreen canvas for rendering the coin rotating around one axis
var offscreenCanvas = document.createElement('canvas');
var cvs = document.getElementById('coin-spin'),
ctx = cvs.getContext('2d'),
w = cvs.width = 400,
h = cvs.height = 400,
cx = w / 2,
cy = h / 2,
a = 0;
var img = new Image();
var frameCount = 0;
var loop = function() {
frameCount++;
// BG
ctx.fillStyle = '#ccc';
ctx.fillRect(0, 0, w, h);
offscreenContext.fillStyle = '#ccc';
offscreenContext.fillRect(0, 0, w, h);
//determine how wide to render the offscreen canvas so we can fake
//rotation around the second axis
var imgRenderWidth = offscreenCanvas.width * Math.sin(frameCount/10.0)
//render the coin rotating around one axis to the offscreen canvas
offscreenContext.save();
offscreenContext.translate(img.width/2, img.height/2);
offscreenContext.rotate(Math.PI / 180 * a);
offscreenContext.translate((0-img.width)/2, (0-img.height)/2);
offscreenContext.drawImage(img, 0,0);
offscreenContext.restore();
// draw offscreen canvas to the screen with our precalculated width
ctx.save();
ctx.drawImage(offscreenCanvas, cx - (imgRenderWidth / 2), cy - (offscreenCanvas.height / 2), imgRenderWidth, offscreenCanvas.height);
ctx.restore();
// axis
ctx.strokeStyle = '#000';
ctx.beginPath();
ctx.moveTo(cx, 0);
ctx.lineTo(cx, h);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0, cy);
ctx.lineTo(w, cy);
ctx.stroke();
//mod angle
a++;
window.requestAnimationFrame(loop);
};
//once the image has loaded, we know what size our offscreen canvas needs to be
img.onload = function() {
offscreenCanvas.width = img.width;
offscreenCanvas.height = img.height;
loop();
};
img.src = 'https://image.ibb.co/gqkeXx/coin.png';
//prepare the offscreen context so we can render to it later
var offscreenContext = offscreenCanvas.getContext('2d');
https://jsfiddle.net/ay3h5vuo/
the rotate() function seems to rotate the whole drawing area. Is there a way to rotate paths individually? I want the center for the rotation to be the object, not the drawing area.
Using save() and restore() still makes rotate take into account the whole drawing area.
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.save();
context.fillStyle = 'red';
context.rotate(0.35);
context.fillRect(40,40, 100, 100);
context.restore();
context.save();
context.fillStyle = 'blue';
context.rotate(0.35);
context.fillRect(200, 40, 100, 100);
context.restore();
<canvas id="canvas" width="500" height="500"></canvas>
Use local space
Instead of drawing object at the position you want them draw everything around its own origin in its local space. The origin is at (0,0) and is the location that the object rotates around.
So if you have a rectangle that you draw with
function drawRect(){
context.fillRect(200, 40, 100, 100);
}
change it so that it is drawn at its origin
function drawRect(){
context.fillRect(-50,-50 , 100, 100);
}
Now you can easily draw it wherevery you want
Start with the setTransform function as that clears any existing tranforms and is a convenient way to set the location of the center of the object will be
ctx.setTransform(1,0,0,1,posX,posY); // clear transform and set center location
if you want to rotate it then add the rotation
ctx.rotate(ang);
and scale with
ctx.scale(scale,scale);
if you have two different scales you should scale before the rotate.
Now just call the draw function
drawRect();
and it is drawn with its center at posX,posY rotated and scaled.
You can combine it all into a function that has the x,y position, the width and the height, scale and rotation. You can include the scale in the setTransform
function drawRect(x,y,w,h,scale,rotation){
ctx.setTransform(scale,0,0,scale,x,y);
ctx.rotate(rotation);
ctx.strokeRect(-w/2,-h/2,w,h);
}
It also applies to an image as a sprite, and I will include a alpha
function drawImage(img,x,y,w,h,scale,rotation,alpha){
ctx.globalAlpha = alpha;
ctx.setTransform(scale,0,0,scale,x,y);
ctx.rotate(rotation);
ctx.drawImage(img,-img.width/2,-img.height/2,img.width,img.height);
}
On a 6 year old laptop that can draw 2000 sprites on firefox every 1/60th of a second, each rotated, scaled, positioned, and with a alpha fade.
No need to mess about with translating back and forward. Just keep all the objects you draw around there own origins and move that origin via the transform.
Update
Lost the demo so here it is to show how to do it in practice.
Just draws a lot of rotated, scaled translated, alphaed rectangles.
By using setTransform you save a lot of time by avoiding save and restore
// create canvas and add resize
var canvas,ctx;
function createCanvas(){
canvas = document.createElement("canvas");
canvas.style.position = "absolute";
canvas.style.left = "0px";
canvas.style.top = "0px";
canvas.style.zIndex = 1000;
document.body.appendChild(canvas);
}
function resizeCanvas(){
if(canvas === undefined){
createCanvas();
}
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx = canvas.getContext("2d");
}
resizeCanvas();
window.addEventListener("resize",resizeCanvas);
// simple function to draw a rectangle
var drawRect = function(x,y,w,h,scale,rot,alpha,col){
ctx.setTransform(scale,0,0,scale,x,y);
ctx.rotate(rot);
ctx.globalAlpha = alpha;
ctx.strokeStyle = col;
ctx.strokeRect(-w/2,-h/2, w, h);
}
// create some rectangles in unit scale so that they can be scaled to fit
// what ever screen size this is in
var rects = [];
for(var i = 0; i < 200; i ++){
rects[i] = {
x : Math.random(),
y : Math.random(),
w : Math.random() * 0.1,
h : Math.random() * 0.1,
scale : 1,
rotate : 0,
dr : (Math.random() - 0.5)*0.1, // rotation rate
ds : Math.random()*0.01, // scale vary rate
da : Math.random()*0.01, // alpha vary rate
col : "hsl("+Math.floor(Math.random()*360)+",100%,50%)",
};
}
// draw everything once a frame
function update(time){
var w,h;
w = canvas.width; // get canvas size incase there has been a resize
h = canvas.height;
ctx.setTransform(1,0,0,1,0,0); // reset transform
ctx.clearRect(0,0,w,h); // clear the canvas
// update and draw each rect
for(var i = 0; i < rects.length; i ++){
var rec = rects[i];
rec.rotate += rec.dr;
drawRect(rec.x * w, rec.y * h, rec.w * w,rec.h * h,rec.scale + Math.sin(time * rec.ds) * 0.4,rec.rotate,Math.sin(time * rec.da) *0.5 + 0.5,rec.col);
}
requestAnimationFrame(update); // do it all again
}
requestAnimationFrame(update);
All transformations in canvas are for the whole drawing area. If you want to rotate around a point you're going to have to translate that point to the origin, do your rotation and translate it back. Something like this is what you want.
Use a rotate function to rotate all of the shape's points around its center.
<!DOCTYPE html>
<html>
<head>
<style>
body
{
margin: 0px;
padding: 0px;
overflow: hidden;
}
canvas
{
position: absolute;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas;
var context;
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var degreesToRadians = function(degrees)
{
return degrees*Math.PI/180;
}
var rotate = function(x, y, cx, cy, degrees)
{
var radians = degreesToRadians(degrees);
var cos = Math.cos(radians);
var sin = Math.sin(radians);
var nx = (cos * (x - cx)) + (sin * (y - cy)) + cx;
var ny = (cos * (y - cy)) - (sin * (x - cx)) + cy;
return new Vector2(nx, ny);
}
var Vector2 = function(x, y)
{
return {x:x,y:y};
}
var Shape = function(points, color)
{
this.color = color;
this.points = points;
};
Shape.prototype.rotate = function(degrees)
{
var center = this.getCenter();
for (var i = 0; i < this.points.length; i++)
{
this.points[i] = rotate(this.points[i].x,this.points[i].y,center.x,center.y,degrees);
}
context.beginPath();
context.arc(center.x,center.y,35,0,Math.PI*2);
context.closePath();
context.stroke();
}
Shape.prototype.draw = function()
{
context.fillStyle = this.color;
context.strokeStyle = "#000000";
context.beginPath();
context.moveTo(this.points[0].x, this.points[0].y);
for (var i = 0; i < this.points.length; i++)
{
context.lineTo(this.points[i].x, this.points[i].y);
//context.fillText(i+1, this.points[i].x, this.points[i].y);
}
context.closePath();
context.fill();
context.stroke();
}
Shape.prototype.getCenter = function()
{
var center = {x:0,y:0};
for (var i = 0; i < this.points.length; i++)
{
center.x += this.points[i].x;
center.y += this.points[i].y;
}
center.x /= this.points.length;
center.y /= this.points.length;
return center;
}
Shape.prototype.translate = function(x, y)
{
for (var i = 0; i < this.points.length; i++)
{
this.points[i].x += x;
this.points[i].y += y;
}
}
var Rect = function(x,y,w,h,c)
{
this.color = c;
this.points = [Vector2(x,y),Vector2(x+w,y),Vector2(x+w,y+h),Vector2(x,y+h)];
}
Rect.prototype = Shape.prototype;
var r = new Rect(50, 50, 200, 100, "#ff0000");
r.draw();
r.translate(300,0);
r.rotate(30);
r.draw();
</script>
</body>
</html>