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();
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've tried for the last few days without too much success to rotate, scale and translate shapes on the canvas.
I've read everything I could find on internet about similar issues but still I cannot seem to be able to adapt it to my own problem.
If everything is drawn on the same scale, I can still drag and drop. If I rotate the shapes, then the mouseOver is messed up since the world coordinates don't correspond anymore with the shape coordinates.
If I scale, then it's impossible to select any shape.
I look at my code and do not understand what I'm doing wrong.
I read some really nice and detailed stackoverflow solutions to similar problems.
For example, user #blindman67 made a suggestion of using a setTransform helper and a getMouseLocal helper for getting the coordinates of the mouse relative to the transformed shape.
inverse transform matrix
I spent some time with that and could not fix my issue.
Here is an example of what I tried. Any suggestion is appreciated.
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth - 40;
canvas.height = window.innerHeight - 60;
const canvasBounding = canvas.getBoundingClientRect();
const offsetX = canvasBounding.left;
const offsetY = canvasBounding.top;
let scale = 1;
let selectedShape = '';
let startX = 0;
let startY = 0;
let endX = 0;
let endY = 0;
let mouseIsDown = false;
let mouseIsMovingShape = false;
let selectedTool = 'SELECT';
let shapes = {};
const selectButton = document.getElementById('select');
const rectangleButton = document.getElementById('rectangle');
canvas.addEventListener('mousedown', canvasMouseDown);
canvas.addEventListener('mouseup', canvasMouseUp);
canvas.addEventListener('mousemove', canvasMouseMove);
function canvasMouseDown(e) {
e.preventDefault();
const mouseX = e.clientX - offsetX;
const mouseY = e.clientY - offsetY;
startX = mouseX;
startY = mouseY;
mouseIsDown = true;
selectedShape = '';
if (selectedTool === 'SELECT') {
for (const shapeId in shapes) {
const shape = shapes[shapeId];
if (shape.mouseIsOver(mouseX, mouseY)) {
selectedShape = shape.id;
shapes[shape.id].isSelected = true;
} else {
shapes[shape.id].isSelected = false;
}
}
}
draw();
}
function canvasMouseUp(e) {
e.preventDefault();
const mouseX = e.clientX - offsetX;
const mouseY = e.clientY - offsetY;
endX = mouseX;
endY = mouseY;
mouseIsDown = false;
const tooSmallShape = Math.abs(endX) - startX < 1 || Math.abs(endY) - startY < 1;
if (tooSmallShape) {
return;
}
if (selectedTool === 'RECTANGLE') {
const newShape = new Shape(selectedTool.toLowerCase(), startX, startY, endX, endY);
shapes[newShape.id] = newShape;
selectedShape = '';
setActiveTool('SELECT');
}
draw();
}
function canvasMouseMove(e) {
e.preventDefault();
const mouseX = e.clientX - offsetX;
const mouseY = e.clientY - offsetY;
const dx = e.movementX;
const dy = e.movementY;
if (mouseIsDown) {
draw();
if (selectedTool === 'SELECT' && selectedShape !== '') {
const shape = shapes[selectedShape];
shape.x += dx;
shape.y += dy;
}
if (selectedTool === 'RECTANGLE') {
drawShapeGhost(mouseX, mouseY);
}
}
}
function draw() {
clear();
for (const shapeId in shapes) {
const shape = shapes[shapeId];
shape.drawShape(ctx);
}
}
function clear() {
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.fillStyle = 'rgba(255, 255, 255, 1)';
ctx.fillRect(0, 0, canvas.width, canvas.height)
}
function drawShapeGhost(x, y) {
ctx.strokeStyle = 'rgba(0, 0, 0, 0.5)';
ctx.strokeRect(startX, startY, x - startX, y - startY);
ctx.stroke();
}
function setActiveTool(tool) {
selectedTool = tool;
if (tool === 'RECTANGLE') {
rectangleButton.classList.add('active');
selectButton.classList.remove('active');
selectedTool = tool;
}
if (tool === 'SELECT') {
rectangleButton.classList.remove('active');
selectButton.classList.add('active');
selectedTool = tool;
}
}
function degreesToRadians(degrees) {
return (Math.PI * degrees) / 180;
};
class Shape {
constructor(shapeType, startX, startY, endX, endY, fill, stroke) {
this.id = shapeType + Date.now();
this.type = shapeType;
this.x = startX;
this.y = startY;
this.width = Math.abs(endX - startX);
this.height = Math.abs(endY - startY);
this.fill = fill || 'rgba(149, 160, 178, 0.8)';
this.stroke = stroke || 'rgba(0, 0, 0, 0.8)';
this.rotation = 0;
this.isSelected = false;
this.scale = 1;
}
drawShape(ctx) {
switch (this.type) {
case 'rectangle':
this._drawRectangle(ctx);
break;
}
}
_drawRectangle(ctx) {
ctx.save();
ctx.scale(this.scale, this.scale);
ctx.translate(this.x + this.width / 2, this.y + this.height / 2);
ctx.rotate(degreesToRadians(this.rotation));
if (this.fill) {
ctx.fillStyle = this.fill;
ctx.fillRect(-this.width / 2, -this.height / 2, this.width, this.height);
}
if (this.stroke !== null) {
ctx.strokeStyle = this.stroke;
ctx.strokeWidth = 1;
ctx.strokeRect(-this.width / 2, -this.height / 2, this.width, this.height);
ctx.stroke();
}
if (this.isSelected) {
ctx.strokeStyle = 'rgba(254, 0, 0, 1)';
ctx.strokeWidth = 1;
ctx.strokeRect(-this.width / 2, -this.height / 2, this.width, this.height)
ctx.stroke();
ctx.closePath();
}
ctx.restore();
}
mouseIsOver(mouseX, mouseY) {
if (this.type === 'rectangle') {
return (mouseX > this.x && mouseX < this.x + this.width && mouseY > this.y && mouseY < this.y + this.height);
}
}
}
const menu = document.getElementById('menu');
const rotation = document.getElementById('rotation');
const scaleSlider = document.getElementById('scale');
menu.addEventListener('click', onMenuClick);
rotation.addEventListener('input', onRotationChange);
scaleSlider.addEventListener('input', onScaleChange);
function onMenuClick(e) {
const tool = e.target.dataset.tool;
if (tool && tool === 'RECTANGLE') {
rectangleButton.classList.add('active');
selectButton.classList.remove('active');
selectedTool = tool;
}
if (tool && tool === 'SELECT') {
rectangleButton.classList.remove('active');
selectButton.classList.add('active');
selectedTool = tool;
}
}
function onRotationChange(e) {
if (selectedShape !== '') {
shapes[selectedShape].rotation = e.target.value;
draw();
}
}
function onScaleChange(e) {
scale = e.target.value;
for (const shapeId in shapes) {
const shape = shapes[shapeId];
shape.scale = scale;
}
draw();
}
function setTransform(ctx, x, y, scaleX, scaleY, rotation) {
const xDx = Math.cos(rotation);
const xDy = Math.sin(rotation);
ctx.setTransform(xDx * scaleX, xDy * scaleX, -xDy * scaleY, xDx * scaleY, x, y);
}
function getMouseLocal(mouseX, mouseY, x, y, scaleX, scaleY, rotation) {
const xDx = Math.cos(rotation);
const xDy = Math.sin(rotation);
const cross = xDx * scaleX * xDx * scaleY - xDy * scaleX * (-xDy) * scaleY;
const ixDx = (xDx * scaleY) / cross;
const ixDy = (-xDy * scaleX) / cross;
const iyDx = (xDy * scaleY) / cross;
const iyDy = (xDx * scaleX) / cross;
mouseX -= x;
mouseY -= y;
const localMouseX = mouseX * ixDx + mouseY * iyDx;
const localMouseY = mouseX * ixDy + mouseY * iyDy;
return {
x: localMouseX,
y: localMouseY,
}
}
function degreesToRadians(degrees) {
return (Math.PI * degrees) / 180
};
function radiansToDegrees(radians) {
return radians * 180 / Math.PI
};
let timer;
function debounce(fn, ms) {
clearTimeout(timer);
timer = setTimeout(() => fn(), ms);
}
canvas {
margin-top: 1rem;
border: 1px solid black;
}
button {
border: 1px solid #adadad;
background-color: transparent;
}
.active {
background-color: lightblue;
}
.menu {
display: flex;
}
.d-flex {
display: flex;
margin-left: 2rem;
}
.rotation input {
margin-left: 1rem;
max-width: 50px;
}
<div id="menu" class="menu">
<button id="select" data-tool="SELECT">select</button>
<button id="rectangle" data-tool="RECTANGLE">rectangle</button>
<div class="d-flex">
<label for="rotation">rotation </label>
<input type="number" id="rotation" value="0">
</div>
<div class="d-flex">
<label for="scale">scale </label>
<input type="range" step="0.1" min="0.1" max="10" value="1" name="scale" id="scale">
</div>
</div>
<canvas id="canvas"></canvas>
If I have time tomorrow I will try to implement the following to your code but I can provide you with a working example of how to get mouse collision precision on a rotated rectangle. I had the same struggle with this and finally found a good explanation and code that I was able to get to work. Check out this website
Now for my own implementation I did not use the method on that website to get my vertices. As you'll see in my code I have a function called updateCorners() in my Square class. I also have objects called this.tl.x and this.tl.y (for each corner).
The formulas are what I use to get vertices of a translated and rotated rectangle and the corner objects are what are used to determine collision. From there I used the distance() function (Pythagorean theorem), the triangleArea() function, and then the clickHit() function which I renamed to collision() and changed some things.
Example in the snippet below
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
canvas.width = 400;
canvas.height = 400;
let shapes = [];
let mouse = {
x: null,
y: null
}
canvas.addEventListener('mousemove', e => {
mouse.x = e.x - canvas.getBoundingClientRect().x;
mouse.y = e.y - canvas.getBoundingClientRect().y;
})
class Square {
constructor(x, y, w, h, c) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.c = c;
this.a = 0;
this.r = this.a * (Math.PI/180);
this.cx = this.x + this.w/2;
this.cy = this.y + this.h/2;
//used to track corners
this.tl = {x: 0, y: 0};
this.tr = {x: 0, y: 0};
this.br = {x: 0, y: 0};
this.bl = {x: 0, y: 0};
}
draw() {
ctx.save();
ctx.translate(this.x, this.y)
ctx.rotate(this.r);
ctx.fillStyle = this.c;
ctx.fillRect(-this.w/2,-this.h/2,this.w,this.h);
ctx.restore();
}
updateCorners() {
this.a += 0.1
this.r = this.a * (Math.PI/180);
let cos = Math.cos(this.r);
let sin = Math.sin(this.r)
//updates Top Left Corner
this.tl.x = (this.x-this.cx)*cos - (this.y-this.cy)*sin+(this.cx-this.w/2);
this.tl.y = (this.x-this.cx)*sin + (this.y-this.cy)*cos+(this.cy-this.h/2)
//updates Top Right Corner
this.tr.x = ((this.x+this.w)-this.cx)*cos - (this.y-this.cy)*sin+(this.cx-this.w/2)
this.tr.y = ((this.x+this.w)-this.cx)*sin + (this.y-this.cy)*cos+(this.cy-this.h/2)
//updates Bottom Right Corner
this.br.x = ((this.x+this.w)-this.cx)*cos - ((this.y+this.h)-this.cy)*sin+(this.cx-this.w/2)
this.br.y = ((this.x+this.w)-this.cx)*sin + ((this.y+this.h)-this.cy)*cos+(this.cy-this.h/2)
//updates Bottom Left Corner
this.bl.x = (this.x-this.cx)*cos - ((this.y+this.h)-this.cy)*sin+(this.cx-this.w/2)
this.bl.y = (this.x-this.cx)*sin + ((this.y+this.h)-this.cy)*cos+(this.cy-this.h/2)
}
}
let square1 = shapes.push(new Square(250, 70, 25, 25, 'red'));
let square2 = shapes.push(new Square(175,210, 100, 50, 'blue'));
let square3 = shapes.push(new Square(50,100, 30, 50, 'purple'));
let square4 = shapes.push(new Square(140,120, 120, 20, 'pink'));
//https://joshuawoehlke.com/detecting-clicks-rotated-rectangles/
//pythagorean theorm using built in javascript hypot
function distance(p1, p2) {
return Math.hypot(p1.x-p2.x, p1.y-p2.y);
}
//Heron's formula used to determine area of triangle
//in the collision() function we will break the rectangle into triangles
function triangleArea(d1, d2, d3) {
var s = (d1 + d2 + d3) / 2;
return Math.sqrt(s * (s - d1) * (s - d2) * (s - d3));
}
function collision(mouse, rect) {
//area of rectangle
var rectArea = Math.round(rect.w * rect.h);
// Create an array of the areas of the four triangles
var triArea = [
// mouse posit checked against tl-tr
triangleArea(
distance(mouse, rect.tl),
distance(rect.tl, rect.tr),
distance(rect.tr, mouse)
),
// mouse posit checked against tr-br
triangleArea(
distance(mouse, rect.tr),
distance(rect.tr, rect.br),
distance(rect.br, mouse)
),
// mouse posit checked against tr-bl
triangleArea(
distance(mouse, rect.br),
distance(rect.br, rect.bl),
distance(rect.bl, mouse)
),
// mouse posit checked against bl-tl
triangleArea(
distance(mouse, rect.bl),
distance(rect.bl, rect.tl),
distance(rect.tl, mouse)
)
];
let triArea2 = Math.round(triArea.reduce(function(a,b) { return a + b; }, 0));
if (triArea2 > rectArea) {
return false;
}
return true;
}
function animate() {
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle = 'black';
ctx.fillText('x: '+mouse.x+',y: '+mouse.y, 50, 50);
for (let i=0; i< shapes.length; i++) {
shapes[i].draw();
shapes[i].updateCorners();
if (collision(mouse, shapes[i])) {
shapes[i].c = 'red';
} else {
shapes[i].c = 'green'
}
}
requestAnimationFrame(animate)
}
animate();
<canvas id="canvas"></canvas>
I'm sure there's many other ways to do this but this is what I was able to understand and get to work. I haven't really messed with scale so I can't help much there.
UPDATE:
Here is a snippet using the method you wanted. Now you can rotate, scale, and translate and still click inside the shape. Be aware I changed your mouse to a global mouse object vice making it a variable in every mouse... function.
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth - 40;
canvas.height = window.innerHeight - 60;
const canvasBounding = canvas.getBoundingClientRect();
const offsetX = canvasBounding.left;
const offsetY = canvasBounding.top;
let scale = 1;
let selectedShape = "";
let startX = 0;
let startY = 0;
let endX = 0;
let endY = 0;
let mouseIsDown = false;
let mouseIsMovingShape = false;
let selectedTool = "SELECT";
let localMouse = { x: null, y: null };
let mouse = { x: null, y: null };
let shapes = {};
const selectButton = document.getElementById("select");
const rectangleButton = document.getElementById("rectangle");
canvas.addEventListener("mousedown", canvasMouseDown);
canvas.addEventListener("mouseup", canvasMouseUp);
canvas.addEventListener("mousemove", canvasMouseMove);
function canvasMouseDown(e) {
e.preventDefault();
mouse.x = e.clientX - offsetX;
mouse.y = e.clientY - offsetY;
startX = mouse.x;
startY = mouse.y;
mouseIsDown = true;
selectedShape = "";
if (selectedTool === "SELECT") {
for (const shapeId in shapes) {
const shape = shapes[shapeId];
if (shape.mouseIsOver()) {
selectedShape = shape.id;
shapes[shape.id].isSelected = true;
} else {
shapes[shape.id].isSelected = false;
}
}
}
draw();
}
function canvasMouseUp(e) {
e.preventDefault();
mouse.x = e.clientX - offsetX;
mouse.y = e.clientY - offsetY;
endX = mouse.x;
endY = mouse.y;
mouseIsDown = false;
const tooSmallShape =
Math.abs(endX) - startX < 1 || Math.abs(endY) - startY < 1;
if (tooSmallShape) {
return;
}
if (selectedTool === "RECTANGLE") {
const newShape = new Shape(
selectedTool.toLowerCase(),
startX,
startY,
endX,
endY
);
shapes[newShape.id] = newShape;
selectedShape = "";
setActiveTool("SELECT");
}
draw();
}
function canvasMouseMove(e) {
e.preventDefault();
mouse.x = e.clientX - offsetX;
mouse.y = e.clientY - offsetY;
const dx = e.movementX;
const dy = e.movementY;
if (mouseIsDown) {
draw();
if (selectedTool === "SELECT" && selectedShape !== "") {
const shape = shapes[selectedShape];
shape.x += dx;
shape.y += dy;
}
if (selectedTool === "RECTANGLE") {
drawShapeGhost(mouse.x, mouse.y);
}
}
}
function draw() {
clear();
for (const shapeId in shapes) {
const shape = shapes[shapeId];
shape.drawShape(ctx);
}
}
function clear() {
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.fillStyle = "rgba(255, 255, 255, 1)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function drawShapeGhost(x, y) {
ctx.strokeStyle = "rgba(0, 0, 0, 0.5)";
ctx.strokeRect(startX, startY, x - startX, y - startY);
ctx.stroke();
}
function setActiveTool(tool) {
selectedTool = tool;
if (tool === "RECTANGLE") {
rectangleButton.classList.add("active");
selectButton.classList.remove("active");
selectedTool = tool;
}
if (tool === "SELECT") {
rectangleButton.classList.remove("active");
selectButton.classList.add("active");
selectedTool = tool;
}
}
function degreesToRadians(degrees) {
return (Math.PI * degrees) / 180;
}
class Shape {
constructor(shapeType, startX, startY, endX, endY, fill, stroke) {
this.id = shapeType + Date.now();
this.type = shapeType;
this.x = startX;
this.y = startY;
this.width = Math.abs(endX - startX);
this.height = Math.abs(endY - startY);
this.fill = fill || "rgba(149, 160, 178, 0.8)";
this.stroke = stroke || "rgba(0, 0, 0, 0.8)";
this.rotation = 0;
this.isSelected = false;
this.scale = { x: 1, y: 1 };
}
drawShape(ctx) {
switch (this.type) {
case "rectangle":
this._drawRectangle(ctx);
break;
}
}
_drawRectangle(ctx) {
ctx.save();
setTransform(
this.x + this.width / 2,
this.y + this.height / 2,
this.scale.x,
this.scale.y,
degreesToRadians(this.rotation)
);
if (this.fill) {
ctx.fillStyle = this.fill;
ctx.fillRect(-this.width / 2, -this.height / 2, this.width, this.height);
}
if (this.stroke !== null) {
ctx.strokeStyle = this.stroke;
ctx.strokeWidth = 1;
ctx.strokeRect(
-this.width / 2,
-this.height / 2,
this.width,
this.height
);
ctx.stroke();
}
if (this.isSelected) {
ctx.strokeStyle = "rgba(254, 0, 0, 1)";
ctx.strokeWidth = 1;
ctx.strokeRect(
-this.width / 2,
-this.height / 2,
this.width,
this.height
);
ctx.stroke();
ctx.closePath();
}
ctx.restore();
}
mouseIsOver() {
localMouse = getMouseLocal(
mouse.x,
mouse.y,
this.x + this.width / 2,
this.y + this.height / 2,
this.scale.x,
this.scale.y,
degreesToRadians(this.rotation)
);
if (this.type === "rectangle") {
if (
localMouse.x > 0 - this.width / 2 &&
localMouse.x < 0 + this.width / 2 &&
localMouse.y < 0 + this.height / 2 &&
localMouse.y > 0 - this.height / 2
) {
return true;
}
}
}
}
const menu = document.getElementById("menu");
const rotation = document.getElementById("rotation");
const scaleSlider = document.getElementById("scale");
menu.addEventListener("click", onMenuClick);
rotation.addEventListener("input", onRotationChange);
scaleSlider.addEventListener("input", onScaleChange);
function onMenuClick(e) {
const tool = e.target.dataset.tool;
if (tool && tool === "RECTANGLE") {
rectangleButton.classList.add("active");
selectButton.classList.remove("active");
selectedTool = tool;
}
if (tool && tool === "SELECT") {
rectangleButton.classList.remove("active");
selectButton.classList.add("active");
selectedTool = tool;
}
}
function onRotationChange(e) {
if (selectedShape !== "") {
shapes[selectedShape].rotation = e.target.value;
draw();
}
}
function onScaleChange(e) {
scale = e.target.value;
for (const shapeId in shapes) {
const shape = shapes[shapeId];
shape.scale.x = scale;
shape.scale.y = scale;
}
draw();
}
function setTransform(x, y, sx, sy, rotate) {
var xdx = Math.cos(rotate); // create the x axis
var xdy = Math.sin(rotate);
ctx.setTransform(xdx * sx, xdy * sx, -xdy * sy, xdx * sy, x, y);
}
function getMouseLocal(mouseX, mouseY, x, y, sx, sy, rotate) {
var xdx = Math.cos(rotate); // create the x axis
var xdy = Math.sin(rotate);
var cross = xdx * sx * xdx * sy - xdy * sx * -xdy * sy;
var ixdx = (xdx * sy) / cross; // create inverted x axis
var ixdy = (-xdy * sx) / cross;
var iydx = (xdy * sy) / cross; // create inverted y axis
var iydy = (xdx * sx) / cross;
mouseX -= x;
mouseY -= y;
var localMouseX = mouseX * ixdx + mouseY * iydx;
var localMouseY = mouseX * ixdy + mouseY * iydy;
return { x: localMouseX, y: localMouseY };
}
function radiansToDegrees(radians) {
return (radians * 180) / Math.PI;
}
let timer;
function debounce(fn, ms) {
clearTimeout(timer);
timer = setTimeout(() => fn(), ms);
}
canvas {
margin-top: 1rem;
border: 1px solid black;
}
button {
border: 1px solid #adadad;
background-color: transparent;
}
.active {
background-color: lightblue;
}
.menu {
display: flex;
}
.d-flex {
display: flex;
margin-left: 2rem;
}
.rotation input {
margin-left: 1rem;
max-width: 50px;
}
<div id="menu" class="menu">
<button id="select" data-tool="SELECT">select</button>
<button id="rectangle" data-tool="RECTANGLE">rectangle</button>
<button id="triangle" data-tool="TRIANGLE">triangle</button>
<div class="d-flex">
<label for="rotation">rotation </label>
<input type="number" id="rotation" value="0">
</div>
<div class="d-flex">
<label for="scale">scale </label>
<input type="range" step="0.1" min="0.1" max="10" value="1" name="scale" id="scale">
</div>
</div>
<canvas id="canvas"></canvas>
I'm trying to make a simple interaction using canvas and Anime.js, using a modified version of one of Julian's examples. The idea is that a circle would enlarge on screen, then the user clicks anywhere on the screen and the circle would contract. I can't get the second animation to play, not sure if this is because my target is not valid or something to do with the timeline? Here is the example.
//Canvas set up
var canvas = document.querySelector('.gameCanvas');
var ctx = canvas.getContext('2d');
var pointerX = 0;
var pointerY = 0;
var circle;
let basicTimeline = anime.timeline();
function setCanvasSize() {
canvas.width = window.innerWidth * 2;
canvas.height = window.innerHeight * 2;
canvas.style.width = window.innerWidth + 'px';
canvas.style.height = window.innerHeight + 'px';
canvas.getContext('2d').scale(2, 2);
}
//Objects and animation
function createCircle(x,y) {
var p = {};
p.x = x;
p.y = y;
p.color = "#fff";
p.radius = anime.random(16, 32);
p.alpha = .5;
p.draw = function() {
ctx.globalAlpha = p.alpha;
ctx.beginPath();
ctx.arc(p.x, p.y, p.radius, 0, 2 * Math.PI, true);
ctx.fillStyle = p.color;
ctx.fill();
}
return p;
}
function renderParticle(anim) {
for (var i = 0; i < anim.animatables.length; i++) {
anim.animatables[i].target.draw();
}
}
function createExpandCircle(x, y) {
circle = createCircle(x, y);
basicTimeline.add({
targets: circle,
radius: anime.random(80, 160),
alpha: {
value: 1,
easing: 'linear',
duration: anime.random(600, 800),
},
duration: anime.random(1200, 1800),
easing: 'linear',
update: renderParticle,
offset: 0
});
}
function contractCircle(){
basicTimeline.add({
targets: circle,
radius: 20,
easing: 'easeOutExpo'
update: renderParticle
});
}
//Mouse Events
var tap = ('ontouchstart' in window || navigator.msMaxTouchPoints) ? 'touchstart' : 'mousedown';
function updateCoords(e) {
pointerX = e.clientX || e.touches[0].clientX;
pointerY = e.clientY || e.touches[0].clientY;
}
document.addEventListener(tap, function(e) {
updateCoords(e);
contractCircle();
}, false);
var centerX = window.innerWidth / 2;
var centerY = window.innerHeight / 2;
createExpandCircle(centerX, centerY);
setCanvasSize();
window.addEventListener('resize', setCanvasSize, false);
So I was able to solve this by adding the following:
ctx.clearRect(0, 0, canvas.width, canvas.height);
To p.draw, and
basicTimeline = anime.timeline();
To contractCircle.
I wrote this canvas animation script in hopes to use it on my portfolio website, but it is basically non-functional in Firefox, and I am not sure why. The script draws stars on the canvas that slowly rotate, and if you hold down the mouse button they spin faster creating trails. It works awesome in chrome, but is extremely slow and choppy in Firefox.
let canvas = document.querySelector('canvas');
let c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let mouse = {
x: window.innerWidth / 2,
y: window.innerHeight / 2
}
let stars = [];
const starCount = 800;
class Star {
constructor(x, y, radius, color){
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.draw = () => {
c.save();
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
c.fillStyle = this.color;
c.shadowColor = this.color;
c.shadowBlur = 15;
c.fill();
c.closePath();
c.restore();
};
this.update = () => {
this.draw();
};
}
}
let colors = [
"#A751CC",
"#DE9AF9",
"#F9E0F9",
"#B5ECFB",
"#5F86F7"
];
(initializeStars = () =>{
for(let i = 0; i < starCount; i++){
let randomColorIndex = Math.floor(Math.random() * 5);
let randomRadius = Math.random() * 2;
let x = (Math.random() * (canvas.width + 400)) - (canvas.width + 400) / 2;
let y = (Math.random() * (canvas.width + 400)) - (canvas.width + 400) / 2;
stars.push(new Star(x, y, randomRadius, colors[randomColorIndex]));
}
})();
let opacity = 1;
let speed = 0.0005;
let time = 0;
let spinSpeed = desiredSpeed => {
speed += (desiredSpeed - speed) * 0.01;
time += speed;
return time;
}
let starOpacity = (desiredOpacity, ease) => {
opacity += (desiredOpacity - opacity) * ease;
return c.fillStyle = `rgba(18, 18, 18, ${opacity})`;
}
let animate = () => {
window.requestAnimationFrame(animate);
c.save();
if(mouseDown){
starOpacity(0.01, 0.03);
spinSpeed(0.012);
}else{
starOpacity(1, 0.01);
spinSpeed(0.001);
}
c.fillRect(0,0, canvas.width, canvas.height);
c.translate(canvas.width / 2, canvas.height / 2);
c.rotate(time);
for(let i = 0; i < stars.length; i++){
stars[i].update();
}
c.restore();
}
window.addEventListener('mousemove', e => {
mouse.x = e.clientX - canvas.width / 2;
mouse.y = e.clientY - canvas.height / 2;
});
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
stars = [];
initializeStars();
});
let mouseDown = false;
window.addEventListener("mousedown", () =>{
mouseDown = true;
});
window.addEventListener("mouseup", () => {
mouseDown = false;
});
animate();
Here is the link to the demo on Code Pen; any help is appreciated.
You can use rect instead of arc to draw your stars:
c.rect(this.x, this.y, 2*this.radius, 2*this.radius);
remove the blur It's extremely expensive:
//c.shadowBlur = 15;
You can use a radial gradient going from opaque in the center to transparent in his stead.
Here is a site, in it a canvas (airplane), which lags when scrolling, appear artifacts, and in different ways, depending on what you scroll - with the mouse wheel or scrollbar. If you comment out parallax or video at the beginning, nothing changes. During the scrolling of calls to the house does not happen. Lags either from behind the airplane script, or because of a clearRect. How can I optimize and get rid of artifacts? The code on the codepen (it works fine)
var scrolled;
var positionsArr = [];
var commonHeight = 0;
var canvas = document.querySelector('#canvas');
var canvasB = document.querySelector('#canvasback');
var ctx = canvas.getContext('2d');
var ctxB = canvasB.getContext('2d');
var centerX, centerY, radius, pointsOffset, radiusRatio, centerXRatio,
firstPoint, lastPoint, jet, blocksPosition, jetPositionY, jetTop, tabletOffset, headerHeight, canvasClearWidth;
var wWidth, mediaMobile, mediaTablet, mediaDesktop1, mediaDesktop2, mediaDesktop3;
jet = new Image();
jet.src = 'http://silencer.website/alkor/images/jet.png';
jet.onload = function () {
adaptive();
}
$(window).on('resize', function () {
adaptive();
});
function adaptive() {
mediaMobile = mediaTablet = mediaDesktop1 = mediaDesktop2 = mediaDesktop3 = false;
wWidth = $(window).width();
// Параметры для дуги по умолчанию
tabletOffset = 0;
radiusRatio = .95;
centerXRatio = 1.25;
// Параметры для дуги на разных разрешениях (перезаписывают параметры по умолчанию)
if (wWidth < 768) {
mediaMobile = true;
}
if (wWidth >= 768 && wWidth < 1024) {
mediaTablet = true;
tabletOffset = 120;
}
if (wWidth >= 1024 && wWidth < 1280) {
mediaDesktop1 = true;
tabletOffset = -40;
radiusRatio = 1.1;
centerXRatio = 1.03;
}
if (wWidth >= 1280 && wWidth < 1440) {
mediaDesktop2 = true;
tabletOffset = -20;
}
if (wWidth >= 1440) {
mediaDesktop3 = true;
tabletOffset = -20;
}
if (!mediaMobile) {
setTimeout(function () {
doCanvas();
}, 500);
} else {
ctx.clearRect(0, 0, canvas.width, canvas.height);
$(window).off('scroll', onScroll);
}
}
function doCanvas() {
$(window).on('scroll', onScroll);
var marginBottom = 120;
commonHeight = 0;
$('.history__item').each(function () {
commonHeight = commonHeight + $(this).height() + marginBottom;
});
commonHeight = commonHeight - marginBottom;
canvasWidth = $('.history').width() * .3;
canvasHeight = $('.history__blocks').height();
canvas.width = canvasWidth;
canvas.height = canvasHeight;
canvasB.width = canvas.width;
canvasB.height = canvas.height;
offsetLeft = $('.history__blocks')[0].offsetLeft;
$('#canvas, #canvasback').css('marginLeft', -offsetLeft);
radius = commonHeight * radiusRatio;
centerX = -commonHeight / centerXRatio + offsetLeft + tabletOffset;
centerY = commonHeight / 2;
pointsOffset = 100;
canvasClearWidth = centerX + radius + 110;
blocksPosition = $('.history__blocks')[0].offsetTop;
jetPositionY = $('.history')[0].offsetTop;
headerHeight = $('.history__title').height();
jetTop = $(window).height() / 2;
jetOnScroll = jetTop - headerHeight - jetPositionY;
positionsArr = [];
lastIndex = $('.history__item').length - 1;
darkened = $('.history__item');
for (var i = 0; i < $('.history__item').length; i++) {
var position = $('.history__item').eq(i)[0].offsetTop - blocksPosition + pointsOffset;
positionsArr.push(position);
if (i == 0) {
firstPoint = position;
}
if (i == $('.history__item').length - 1) {
lastPoint = position;
}
}
draw();
drawBackground();
setTimeout(function () {
if (mediaTablet) {
jetPositionLine(firstPoint);
} else {
jetPosition(firstPoint);
}
}, 100);
}
function drawBackground() {
if (mediaTablet) {
drawLine();
} else {
drawArc();
}
}
function draw(currentY) {
for (var i = 0; i < positionsArr.length; i++) {
addPoint(positionsArr[i], currentY, i);
}
}
function drawArc() {
var firstPointRad = Math.asin((centerY - firstPoint) / radius);
var lastPointRad = Math.asin((centerY - lastPoint) / radius);
ctxB.beginPath();
ctxB.lineWidth = 3;
ctxB.save();
ctxB.arc(centerX, centerY, radius, 1.5, lastPointRad, true);
ctxB.strokeStyle = '#99daf0';
ctxB.setLineDash([8, 5]);
ctxB.lineDashOffset = 1;
ctxB.globalCompositeOperation = 'destination-over';
ctxB.stroke();
ctxB.restore();
}
function drawLine() {
ctxB.beginPath();
ctxB.lineWidth = 3;
ctxB.save();
ctxB.lineTo(tabletOffset, firstPoint);
ctxB.lineTo(tabletOffset, lastPoint);
ctxB.strokeStyle = '#99daf0';
ctxB.setLineDash([8, 5]);
ctxB.lineDashOffset = 1;
ctxB.globalCompositeOperation = 'destination-over';
ctxB.stroke();
ctxB.restore();
}
function addPoint(y, currentY, i) {
if (mediaTablet) {
var currentX = tabletOffset;
} else {
var angle = Math.asin((centerY - y) / radius);
var currentX = centerX + radius * (Math.cos(angle));
}
ctx.beginPath();
ctx.arc(currentX, y, 8, 0, 2 * Math.PI, false);
ctx.lineWidth = 3;
ctx.fillStyle = '#00a3da';
ctx.globalCompositeOperation = 'source-over';
if (currentY + 10 >= y) {
ctx.strokeStyle = '#fff';
darkened.eq(i).removeClass('darkened');
} else {
ctx.strokeStyle = '#99daf0';
darkened.eq(i).addClass('darkened');
}
ctx.fill();
ctx.stroke();
}
function jetPosition(y) {
var angle = Math.asin((centerY - y) / radius);
var currentX = centerX + radius * (Math.cos(angle) - 1);
var firstPointRad = Math.asin((centerY - firstPoint) / radius);
// if (toUp) { // Самолетик вверх-вниз
var jetAngle = Math.acos((centerY - y) / radius);
// } else {
// var jetAngle = Math.acos((centerY - y) / radius) + Math.PI;
// }
ctx.beginPath();
ctx.arc(centerX, centerY, radius, -angle, -firstPointRad, true);
ctx.globalCompositeOperation = 'source-over';
ctx.lineWidth = 3;
ctx.strokeStyle = '#fff';
ctx.stroke();
draw(y);
ctx.save();
ctx.translate(currentX + radius, y)
ctx.rotate(jetAngle - 1.6);
ctx.globalCompositeOperation = 'source-over';
ctx.drawImage(jet, -106, -80, 212, 160);
ctx.restore();
}
function jetPositionLine(y) {
ctx.beginPath();
ctx.lineTo(tabletOffset, firstPoint);
ctx.lineTo(tabletOffset, y);
ctx.lineWidth = 3;
ctx.strokeStyle = '#fff';
ctx.stroke();
draw(y);
ctx.beginPath();
ctx.save();
ctx.globalCompositeOperation = 'source-over';
ctx.drawImage(jet, tabletOffset - 106, y - 80, 212, 160);
ctx.restore();
}
function onScroll() {
requestAnimationFrame(scrollCanvas);
};
function scrollCanvas() {
var prevScroll = scrolled;
scrolled = window.pageYOffset;
toUp = prevScroll < scrolled;
var positionY = scrolled + jetOnScroll;
if (positionY >= firstPoint) {
if (positionY <= lastPoint) {
ctx.clearRect(0, 0, canvasClearWidth, canvasHeight);
if (mediaTablet) {
jetPositionLine(positionY);
} else {
jetPosition(positionY);
}
} else {
$('.history__item').eq(lastIndex).removeClass('darkened');
}
}
if (!mediaMobile && !mediaTablet) {
parallaxScroll();
}
}