I'm build a kind of javascript map with javascript and the Raphael lib.
I'm able to zoom on an object when clicked, but I want it to be animated (like slowly diving in and so on). Is there a way to do so without reinventing the wheel?
There is no reason that the viewbox of an svg object cannot be animated -- Raphael simply doesn't provide such functionality out of the box. Creating a plugin is reasonably straightforward, however. For instance:
Raphael.fn.animateViewBox = function animateViewBox( x, y, w, h, duration, easing_function, callback )
{
var cx = this._viewBox ? this._viewBox[0] : 0,
dx = x - cx,
cy = this._viewBox ? this._viewBox[1] : 0,
dy = y - cy,
cw = this._viewBox ? this._viewBox[2] : this.width,
dw = w - cw,
ch = this._viewBox ? this._viewBox[3] : this.height,
dh = h - ch,
self = this;;
easing_function = easing_function || "linear";
var interval = 25;
var steps = duration / interval;
var current_step = 0;
var easing_formula = Raphael.easing_formulas[easing_function];
var intervalID = setInterval( function()
{
var ratio = current_step / steps;
self.setViewBox( cx + dx * easing_formula( ratio ),
cy + dy * easing_formula( ratio ),
cw + dw * easing_formula( ratio ),
ch + dh * easing_formula( ratio ), false );
if ( current_step++ >= steps )
{
clearInterval( intervalID );
callback && callback();
}
}, interval );
}
Any paper instantiated after this plugin is installed can use animateViewBox in exactly the same method Raphael's built-in animate method works. For instance...
var paper = Raphael( 0, 0, 640, 480 );
paper.animateViewBox( 100, 100, 320, 240, 5000, '<>', function()
{
alert("View box updated! What's next?" );
} );
Demonstration staged here.
Raphael animations work by animating element attributes. When you call element.animate, you provide the final object parameters, the time it takes to get there and possibly an easing function if you don't want it to be linear.
For example, to scale up/down an circle you might consider this example: http://jsfiddle.net/eUfCg/
// Creates canvas 320 × 200 at 10, 50
var paper = Raphael(10, 50, 320, 200);
// Creates circle at x = 50, y = 40, with radius 10
var circle = paper.circle(50, 40, 10);
// Sets the fill attribute of the circle to red (#f00)
circle.attr("fill", "#f00");
// Sets the stroke attribute of the circle to white
circle.attr("stroke", "#fff");
var zoomed = false;
circle.click(function () {
if (zoomed) {
this.animate({ transform: "s1" }, 500);
zoomed = false;
} else {
this.animate({ transform: "s4" }, 500);
zoomed = true;
}
});
Which animates the transform property of the circle. To scale your map you should put all of the elements inside a group, and animate the transform property of the group, considering the scale and translation that you want to end up with.
See http://raphaeljs.com/reference.html#Element.transform for more information on the transform property.
Related
My three.js scene is completely distorted until I move the mouse somewhere on the site.
You can see the nature of the distortion on the image below:
When I move the mouse, the scene suddenly pops and everything is fine. It doesn't seem to matter where exactly the cursor is within the site, it doesn't have to be over the canvas where my scene is rendered.
This is how the scene looks after moving the mouse:
The following three.js related dependencies are used:
"three": "^0.108.0"
"three-orbitcontrols": "^2.102.2"
"three.meshline": "^1.2.0"
I tried updating three to the latest version (0.116.1), but that didn't solve the issue either. I managed to replicate this issue on Firefox and Edge, but not on Chrome.
Some extra context: we use OffscreenCanvas for better performance, the mouse positions are sent from the main thread to the web worker on mousemove event, we use that information to slightly move the camera and the background (with offsets). I temporarily removed to mousemove handler logic from the web worker code and the issue still popped up, so it's probably unrelated. We use tween.js to make the camera animations smooth.
Relevant code snippets:
Scene setup:
const {scene, camera} = makeScene(elem, cameraPosX, 0, 60, 45);
const supportsWebp = (browser !== 'Safari');
imageLoader.load(backgroundImage, mapImage => {
const texture = new THREE.CanvasTexture(mapImage);
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
texture.minFilter = THREE.LinearFilter;
// Repeat background so we don't run out of it during offset changes on mousemove
texture.wrapS = THREE.MirroredRepeatWrapping;
texture.wrapT = THREE.MirroredRepeatWrapping;
scene.background = texture;
});
// Creating objects in the scene
let orbitingPlanet = getPlanet(0xffffff, true, 1 * mobilePlanetSizeAdjustment);
scene.add(orbitingPlanet);
// Ellipse class, which extends the virtual base class Curve
let curveMain = new THREE.EllipseCurve(
0, 0, // ax, aY
80, 30, // xRadius, yRadius
0, 2 * Math.PI, // aStartAngle, aEndAngle
false, // aClockwise
0.2 // aRotation
);
let ellipseMainGeometry = new THREE.Path(curveMain.getPoints(100)).createPointsGeometry(100);
let ellipseMainMaterial = new MeshLine.MeshLineMaterial({
color: new THREE.Color(0xffffff),
opacity: 0.2,
transparent: true,
});
let ellipseMain = new MeshLine.MeshLine();
ellipseMain.setGeometry(ellipseMainGeometry, function(p) {
return 0.2; // Line width
});
const ellipseMainMesh = new THREE.Mesh(ellipseMain.geometry, ellipseMainMaterial );
scene.add(ellipseMainMesh);
// Create a halfish curve on which one of the orbiting planets will move
let curveMainCut = new THREE.EllipseCurve(
0, 0, // ax, aY
80, 30, // xRadius, yRadius
0.5 * Math.PI, 1.15 * Math.PI, // aStartAngle, aEndAngle
false, // aClockwise
0.2 // aRotation
);
let lastTweenRendered = Date.now();
let startRotation = new THREE.Vector3(
camera.rotation.x,
camera.rotation.y,
camera.rotation.z);
let tweenie;
return (time, rect) => {
camera.aspect = state.width / state.height;
camera.updateProjectionMatrix();
let pt1 = curveMainCut.getPointAt(t_top_faster);
orbitingPlanet.position.set(pt1.x, pt1.y, 1);
t_top_faster = (t_top_faster >= 1) ? 0 : t_top_faster += 0.001;
// Slightly rotate the background on mouse move
if (scene && scene.background) {
// The rotation mush be between 0 and 0.01
scene.background.rotation =
Math.max(-0.001,Math.min(0.01, scene.background.rotation + 0.00005 * target.x));
let offsetX = scene.background.offset.x + 0.00015 * target.x;
let offsetY = scene.background.offset.y + 0.00015 * target.y;
scene.background.offset = new THREE.Vector2(
(offsetX > -0.05 && offsetX < 0.05) ? offsetX : scene.background.offset.x,
(offsetY > -0.05 && offsetY < 0.05) ? offsetY : scene.background.offset.y);
}
lastTweenRendered = tweenAnimateCamera(lastTweenRendered, tweenie, camera, startRotation, 200);
renderer.render(scene, camera);
};
makeScene function:
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(fieldOfView, state.width / state.height, 0.1, 100000000);
camera.position.set(camPosX, camPosY, camPosZ);
camera.lookAt(0, 0, 0);
scene.add(camera);
return {scene, camera};
Camera animation based on mouse positions:
function tweenAnimateCamera(lastTweenRendered, tween, camera, startRotation, period) {
target.x = (1 - mouse.x) * 0.002;
target.y = (1 - mouse.y) * 0.002;
let now = Date.now();
if ((
// Don't let the camera go too far
startRotation.x > -0.01 && startRotation.x < 0.01) &&
now - lastTweenRendered > (period / 2)) {
if (tween) {
tween.stop();
}
lastTweenRendered = now;
let endRotation = new THREE.Vector3(
camera.rotation.x + 0.005 * (target.y - camera.rotation.x),
camera.rotation.y + 0.005 * (target.x - camera.rotation.y),
camera.rotation.z);
tween = new TWEEN.Tween(startRotation)
.to(endRotation, period * 2)
.easing(TWEEN.Easing.Quadratic.InOut)
.onUpdate(function (v) {
camera.rotation.set(v.x, v.y, v.z);
})
.onComplete(function(v) {
startRotation = v.clone();
});
tween.start();
}
TWEEN.update();
return lastTweenRendered
}
Mouse position receiver logic:
if (e.data.type === 'mousePosUpdate') {
if (e.data.x !== -100000 && e.data.y !== -100000) {
mouse.x = ( e.data.x - state.width / 2 );
mouse.y = ( e.data.y - state.height / 2 );
target.x = ( 1 - mouse.x ) * 0.002;
target.y = ( 1 - mouse.y ) * 0.002;
}
}
Render loop:
function render(time) {
time *= 0.001;
for (const {elem, fn, ctx} of sceneElements) {
// get the viewport relative position of this element
canvasesUpdatedPos.forEach( canvasUpdate => {
if (canvasUpdate.id === elem.id) {
elem.rect = canvasUpdate.rect;
}
});
const rect = elem.rect;
const bottom = rect.bottom;
const height = rect.height;
const left = rect.left;
const right = rect.right;
const top = rect.top;
const width = rect.width;
const rendererCanvas = renderer.domElement;
const isOffscreen =
bottom < 0 ||
top > state.height ||
right < 0 ||
left > state.width;
if (!isOffscreen && width !== 0 && height !== 0) {
// make sure the renderer's canvas is big enough
let isResize = resizeRendererToDisplaySize(renderer, height, width);
// make sure the canvas for this area is the same size as the area
if (ctx.canvas.width !== width || ctx.canvas.height !== height) {
ctx.canvas.width = width;
ctx.canvas.height = height;
state.width = width;
state.height = height;
}
renderer.setScissor(0, 0, width, height);
renderer.setViewport(0, 0, width, height);
fn(time, rect);
// copy the rendered scene to this element's canvas
ctx.globalCompositeOperation = 'copy';
ctx.drawImage(
rendererCanvas,
0, rendererCanvas.height - height, width, height, // src rect
0, 0, width, height); // dst rect
}
}
// Limiting to 35 FPS.
setTimeout(function() {
if (!stopAnimating) {
requestAnimationFrame(render);
}
}, 1000 / 35);
}
I don't see where you're initiating target and mouse anywhere. My best guess is that target.x, target.y or mouse.x, mouse.y are undefined or 0, and it's probably causing a division by 0, or a calculation that returns NaN, which is giving you that infinitely stretched texture. You should be able to fix this if you initiate those vectors:
var target = new THREE.Vector2();
var mouse = new THREE.Vector2();
First of anyone running into similar issues please take a look at Marquizzo's answer and Ethan Hermsey's comment (on the question) as well, since they provided a good possible cause for this issue, although the issue was different in my case.
The distortion was related to the OffscreenCanvas in our case. When the application starts we send the OffscreenCanvas along with it's size to the web worker:
const rect = element.getBoundingClientRect();
const offScreenCanvas = element.transferControlToOffscreen();
worker.post({
type: 'canvas',
newCanvas: offScreenCanvas,
width: rect.width,
height: rect.height
}, [offScreenCanvas]);
The cause of the issue was the height, which was incorrect in certain cases, 1px to be precise in the example pictured in the question. The incorrect height popped up because of a race condition, in a separate script we used to set up the height of certain canvas container elements with the following script:
$(".fullscreen-block").css({ height: var wh = $(window).height() });
However, we usually sent the size of the canvas to the worker before this happened. Substituting this JS code with a simple CSS rule solved this issue:
.fullscreen-block {
height: 100vh;
}
So, in the end, the issue was not related to the mouse event's handled by us, I can only guess why moving the mouse fixed the distortion. I'd say Firefox probably revalidates/recalculates the size of DOM elements when the mouse is moved and we were notified about size changes, causing the animation to pop to the correct size and state.
I have two things that I want to display with p5, one is a 2D background and the other is a 3D WebGL foreground, both generated by p5. What I noticed is that even if I draw the 2D background before the 3D stuff in the draw() function, the 3D stuff will still be partially covered by the background when rotateX() or rotateY() is called. It looks kind of like this:
I suspect what's happening is that the 2d and 3d stuff are both on the same z-plane, therefore when the foreground is rotated some of it gets covered by the background which now is in the front compared to the covered parts.
So my question is how can I keep the background completely in the back (i.e. not covering foreground regardless of the rotation)?
Below is my current implementation, the 2d background is generated in an offscreen canvas then put onto the main canvas with image() where the 3d stuff is generated, but I'll take any other approaches.
let bg;
p.setup = () => {
p.createCanvas(width,height,p.WEBGL);
bg = p.createGraphics(width,height);
}
p.draw = () => {
... // draw background bg
p.image(bg,x,y); // draw background on canvas
... // draw foreground
p.rotateX(degrees);//rotate
}
The best way to accomplish this is by clearing the WebGL depth buffer. This is buffer stores the depth for every pixel that has been draw so far so that as subsequent triangles are drawn they can be clipped if some or all of them is behind whatever was previously drawn at that location. This buffer is automatically cleared in between calls to draw() in p5.js but you can also call it yourself mid-frame:
let bg;
let zSlider;
let glContext;
function setup() {
let c = createCanvas(200, 200, WEBGL);
glContext = c.GL;
bg = createGraphics(width, height);
bg.background('red');
for (let y = 0; y < height; y += 20) {
for (let x = 0; x < width; x += 20) {
if ((x / 20 + y / 20) % 2 === 0) {
bg.fill('black');
} else {
bg.fill(
map(x + y, 0, width + height, 0, 360),
map(y, 0, height, 50, 100),
map(x, 0, width, 50, 100)
);
}
bg.square(x, y, 20)
}
}
zSlider = createSlider(0, width * 2, width);
zSlider.position(10, 10);
}
function draw() {
image(bg, -width / 2, -height / 2, width, height);
// Clear the z-buffer, subsequent drawing commands will not clip, even if they
// intersect with or are behind previously drawn elements (like our background
// image)
glContext.clear(glContext.DEPTH_BUFFER_BIT);
push();
translate(0, 0, (zSlider.value() - width) * 2);
rotateX(millis() / 1000 * PI / 4);
rotateY(millis() / 1000 * PI / 8);
box(100);
pop();
}
<script src="https://cdn.jsdelivr.net/npm/p5#1.3.1/lib/p5.js"></script>
There is also kludgy solution that doesn't rely on calling WebGL internals, but I have only been able to make it work for square canvases:
Switch to an orthographic camera mode before drawing your background image.
Translate in the negative Z direction as far as possible without going beyond the "far" clipping plane.
Draw your background image.
Pop the state back to the normal perspective camera.
This uses orthographic projection to allow you to draw the background image behind the rest of the scene without diminishing size due to perspective. However I haven't come up with a fool proof way to determine what the perfect translation value is, nor how to reliably setup the orthographic project to control where the "far" clipping plane is.
let bg;
let zSlider;
function setup() {
createCanvas(200, 200, WEBGL);
bg = createGraphics(width, height);
bg.background('red');
for (let y = 0; y < height; y += 20) {
for (let x = 0; x < width; x += 20) {
if ((x / 20 + y / 20) % 2 === 0) {
bg.fill('black');
} else {
bg.fill(
map(x + y, 0, width + height, 0, 360),
map(y, 0, height, 50, 100),
map(x, 0, width, 50, 100)
);
}
bg.square(x, y, 20)
}
}
zSlider = createSlider(0, width * 2, width);
zSlider.position(10, 10);
}
function draw() {
push();
ortho();
translate(0, 0, min(width, height) * -0.13);
image(bg, -width / 2, -height / 2, width, height);
pop();
push();
translate(0, 0, (zSlider.value() - width) * 2);
rotateX(millis() / 1000 * PI / 4);
rotateY(millis() / 1000 * PI / 8);
box(100);
pop();
}
<script src="https://cdn.jsdelivr.net/npm/p5#1.3.1/lib/p5.js"></script>
I am trying to make an animation with texture atlas:
and it works good when the Character is facing right. I try to flip it horizontally, but it gets wrong position:
Here is my current code:
<canvas id="c" width="200" height="100" style="background: #000"></canvas>
var metaData = [
{x:0,y:0,w:35,h:38,offsetX:3,offsetY:9},
{x:37,y:0,w:31,h:37,offsetX:6,offsetY:10},
{x:70,y:0,w:65,h:47,offsetX:0,offsetY:1},
{x:137,y:0,w:65,h:47,offsetX:0,offsetY:1},
{x:204,y:0,w:61,h:46,offsetX:1,offsetY:1},
{x:267,y:0,w:42,h:46,offsetX:1,offsetY:1},
{x:311,y:0,w:43,h:44,offsetX:1,offsetY:3},
{x:356,y:0,w:38,h:37,offsetX:6,offsetY:10},
{x:396,y:0,w:35,h:34,offsetX:6,offsetY:13},
{x:433,y:0,w:33,h:37,offsetX:7,offsetY:10},
{x:468,y:0,w:36,h:40,offsetX:5,offsetY:7},
{x:506,y:0,w:34,h:39,offsetX:6,offsetY:8}
],
dx = 0, //position x
dy = 0, //position y
index = 0; //frame index
(function draw() {
context2D.clearRect(0,0,c.width,c.height);
var cur = metaData[index];
if(facingRight) {
context2D.drawImage(
img,
cur.x, cur.y,
cur.w, cur.h,
dx + cur.offsetX, dy + cur.offsetY,
cur.w, cur.h
);
} else {
context2D.save();
context2D.translate(cur.w,0);
context2D.scale(-1,1);
context2D.drawImage(
img,
cur.x, cur.y,
cur.w, cur.h,
dx, dy + cur.offsetY,
cur.w, cur.h
);
context2D.restore();
}
index = ++index % metaData.length;
setTimeout(draw,100);
})();
I use scale(-1,1) to flip sprite, but I have no idea how to keep it at the same postion like facing right. Should I fix the offset value?
Please, any help will be appreciated :)
You would save you a lot of time taking an Image editor and making all your sprites fit in same-sized areas along the whole sprite-sheet.
No need metadata weirdness, code is way simpler (a single w, a single h, x = w * i etc.
For example, your largest sprite is around 70px wide, so you should fit all your other sprites in one of such boxes :
Now, it seems that all your sprites share the same position of the front foot. So you should use it as the anchor point for aligning all your sprites.
Something like this :
Note how for all the sprites, the front foot is always at the same position relatively to its own box.
Now it's quite easy to code animation of this sprite-sheet, and even to flip it :
const ssheet = new Image();
ssheet.src = 'https://i.stack.imgur.com/kXKIc.png'; // same without borders
ssheet.onload = startSheetAnim;
function startSheetAnim(evt) {
const ctx = c.getContext('2d');
const h = 49;
const w = 70;
let i = 0;
function anim() {
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, c.width, c.height);
ctx.drawImage(ssheet,
(i * w), 1, w, h,
0, 0, w, h
);
// scale (flip-x) and translate
ctx.setTransform(-1, 0, 0, 1, w * 2, 0);
ctx.drawImage(ssheet,
(i * w), 1, w, h,
0, 0, w, h
);
i = (i + 1) % 12
setTimeout(anim, 100);
}
anim();
}
<canvas id="c"></canvas>
I have an image which is a background containing a boxed area like this:
I know the exact positions of the corners of that shape, and I'd like to place another image within it. (So it appears to be inside the box).
I'm aware of the drawImage method for HTML5 canvas, but it seems to only support x, y, width, height parameters rather than exact coordinates. How might I draw an image onto a canvas at a specific set of coordinates, and ideally have the browser itself handle stretching the image.
Quadrilateral transform
One way to go about this is to use Quadrilateral transforms. They are different than 3D transforms and would allow you to draw to a canvas in case you want to export the result.
The example shown here is simplified and uses basic sub-divison and "cheats" on the rendering itself - that is, it draws in a small square instead of the shape of the sub-divided cell but because of the small size and the overlap we can get away with it in many non-extreme cases.
The proper way would be to split the shape into two triangles, then scan pixel wise in the destination bitmap, map the point from destination triangle to source triangle. If the position value was fractional you would use that to determine pixel interpolation (f.ex. bi-linear 2x2 or bi-cubic 4x4).
I do not intend to cover all this in this answer as it would quickly become out of scope for the SO format, but the method would probably be suitable in this case unless you need to animate it (it is not performant enough for that if you want high resolution).
Method
Lets start with an initial quadrilateral shape:
The first step is to interpolate the Y-positions on each bar C1-C4 and C2-C3. We're gonna need current position as well as next position. We'll use linear interpolation ("lerp") for this using a normalized value for t:
y1current = lerp( C1, C4, y / height)
y2current = lerp( C2, C3, y / height)
y1next = lerp(C1, C4, (y + step) / height)
y2next = lerp(C2, C3, (y + step) / height)
This gives us a new line between and along the outer vertical bars.
Next we need the X positions on that line, both current and next. This will give us four positions we will fill with current pixel, either as-is or interpolate it (not shown here):
p1 = lerp(y1current, y2current, x / width)
p2 = lerp(y1current, y2current, (x + step) / width)
p3 = lerp(y1next, y2next, (x + step) / width)
p4 = lerp(y1next, y2next, x / width)
x and y will be the position in the source image using integer values.
We can use this setup inside a loop that will iterate over each pixel in the source bitmap.
Demo
The demo can be found at the bottom of the answer. Move the circular handles around to transform and play with the step value to see its impact on performance and result.
The demo will have moire and other artifacts, but as mentioned earlier that would be a topic for another day.
Snapshot from demo:
Alternative methods
You can also use WebGL or Three.js to setup a 3D environment and render to canvas. Here is a link to the latter solution:
Three.js
and an example of how to use texture mapped surface:
Three.js texturing (instead of defining a cube, just define one place/face).
Using this approach will enable you to export the result to a canvas or an image as well, but for performance a GPU is required on the client.
If you don't need to export or manipulate the result I would suggest to use simple CSS 3D transform as shown in the other answers.
/* Quadrilateral Transform - (c) Ken Nilsen, CC3.0-Attr */
var img = new Image(); img.onload = go;
img.src = "https://i.imgur.com/EWoZkZm.jpg";
function go() {
var me = this,
stepEl = document.querySelector("input"),
stepTxt = document.querySelector("span"),
c = document.querySelector("canvas"),
ctx = c.getContext("2d"),
corners = [
{x: 100, y: 20}, // ul
{x: 520, y: 20}, // ur
{x: 520, y: 380}, // br
{x: 100, y: 380} // bl
],
radius = 10, cPoint, timer, // for mouse handling
step = 4; // resolution
update();
// render image to quad using current settings
function render() {
var p1, p2, p3, p4, y1c, y2c, y1n, y2n,
w = img.width - 1, // -1 to give room for the "next" points
h = img.height - 1;
ctx.clearRect(0, 0, c.width, c.height);
for(y = 0; y < h; y += step) {
for(x = 0; x < w; x += step) {
y1c = lerp(corners[0], corners[3], y / h);
y2c = lerp(corners[1], corners[2], y / h);
y1n = lerp(corners[0], corners[3], (y + step) / h);
y2n = lerp(corners[1], corners[2], (y + step) / h);
// corners of the new sub-divided cell p1 (ul) -> p2 (ur) -> p3 (br) -> p4 (bl)
p1 = lerp(y1c, y2c, x / w);
p2 = lerp(y1c, y2c, (x + step) / w);
p3 = lerp(y1n, y2n, (x + step) / w);
p4 = lerp(y1n, y2n, x / w);
ctx.drawImage(img, x, y, step, step, p1.x, p1.y, // get most coverage for w/h:
Math.ceil(Math.max(step, Math.abs(p2.x - p1.x), Math.abs(p4.x - p3.x))) + 1,
Math.ceil(Math.max(step, Math.abs(p1.y - p4.y), Math.abs(p2.y - p3.y))) + 1)
}
}
}
function lerp(p1, p2, t) {
return {
x: p1.x + (p2.x - p1.x) * t,
y: p1.y + (p2.y - p1.y) * t}
}
/* Stuff for demo: -----------------*/
function drawCorners() {
ctx.strokeStyle = "#09f";
ctx.lineWidth = 2;
ctx.beginPath();
// border
for(var i = 0, p; p = corners[i++];) ctx[i ? "lineTo" : "moveTo"](p.x, p.y);
ctx.closePath();
// circular handles
for(i = 0; p = corners[i++];) {
ctx.moveTo(p.x + radius, p.y);
ctx.arc(p.x, p.y, radius, 0, 6.28);
}
ctx.stroke()
}
function getXY(e) {
var r = c.getBoundingClientRect();
return {x: e.clientX - r.left, y: e.clientY - r.top}
}
function inCircle(p, pos) {
var dx = pos.x - p.x,
dy = pos.y - p.y;
return dx*dx + dy*dy <= radius * radius
}
// handle mouse
c.onmousedown = function(e) {
var pos = getXY(e);
for(var i = 0, p; p = corners[i++];) {if (inCircle(p, pos)) {cPoint = p; break}}
}
window.onmousemove = function(e) {
if (cPoint) {
var pos = getXY(e);
cPoint.x = pos.x; cPoint.y = pos.y;
cancelAnimationFrame(timer);
timer = requestAnimationFrame(update.bind(me))
}
}
window.onmouseup = function() {cPoint = null}
stepEl.oninput = function() {
stepTxt.innerHTML = (step = Math.pow(2, +this.value));
update();
}
function update() {render(); drawCorners()}
}
body {margin:20px;font:16px sans-serif}
canvas {border:1px solid #000;margin-top:10px}
<label>Step: <input type=range min=0 max=5 value=2></label><span>4</span><br>
<canvas width=620 height=400></canvas>
You can use CSS Transforms to make your image look like that box. For example:
img {
margin: 50px;
transform: perspective(500px) rotateY(20deg) rotateX(20deg);
}
<img src="https://via.placeholder.com/400x200">
Read more about CSS Transforms on MDN.
This solution relies on the browser performing the compositing. You put the image that you want warped in a separate element, overlaying the background using position: absolute.
Then use CSS transform property to apply any perspective transform to the overlay element.
To find the transform matrix you can use the answer from: How to match 3D perspective of real photo and object in CSS3 3D transforms
I am developing an HTML5 canvas based mini-game and I can't seem to organize linear animation.
I am using this code for adding a "target" object to the canvas:
var target = new Kinetic.Shape(function(){
var context = this.getContext();
context.drawImage(images.target, x, y, 2*radius, 2*radius);
context.beginPath();
context.rect(x, y, 2*radius, 2*radius);
context.closePath();
});
gameLayer.add(target);
I need to animate this object with linear animation, trying this code:
var mx = x;
setInterval(function(){
mx -= 1;
target.setPosition(mx, y);
gameLayer.draw();
}, 500);
But, it didn't work! What is wrong?
I don't know why it doesn't work, but I found the way to do as:
var mx = x;
var my = target.y;
target.transitionTo({
x: mx,
y: my,
rotation: 0,
scale: {x: 1, y: 1},
duration: 1, //time to transition in second
});
You can see more details at: http://www.html5canvastutorials.com/kineticjs/html5-canvas-linear-transition-tutorial-with-kineticjs/
They have an Animation function. So you can
var myAnimationName = new Kinetic.Animation(function (frame) {
console.log(frame.time);
target.setX(target.getX() + 1);
if (target.getX() < somePosition) {
target.setX(somePosition);
this.stop();
}
}, layer);
myAnimationName.start();
You can use also frame.time if needed