I'm trying to build a d3js chart that zooms only on the X-axis but allows panning on both axes. The example below has the effect I desire:
https://jsfiddle.net/xpr364uo/
However, I'm having trouble translating this into my own code. For one, I'm rendering to canvas so I don't have the ability to set the "transform" attribute on some element. Also my zooming uses rescaleX/rescaleY on copies of the scales, as is the "new way" to do zooming via d3-zoom, from what I understand:
const zoomBehavior = zoom().on('zoom', () => {
const xDomain = event.transform.rescaleX(x2).domain();
const yDomain = event.transform.rescaleY(y2).domain();
xScale.domain(xDomain);
yScale.domain(yDomain);
render();
});
This works to zoom/pan on both axes. How can I modify it to get the same affect as in the fiddle? What am I supposed to do with deltaPanY (from the fiddle), in my code?
You could keep track of a second zoom transform (I'll call this yTransform) and use this to rescale the y axis. As you want the x to zoom normally, you can still use d3.event.transform.rescaleX() to rescale on the X axis, while the yTransform can be used to rescale on the Y axis.
When panning, the y translate value of yTransform should be updated with the current zoom state. Conversely, when zooming, yTransform should be used to override the change in the zoom state's y translate.
Perhaps something like:
var yTransform = d3.zoomIdentity; // initial state for the y transform
var zoom = d3.zoom()
.on("zoom", function() {
var t = d3.event.transform; // zoom state
x2 = t.rescaleX(x); // rescale x as normal (t.y is irrelevant)
// for a pan event, update the y translate
if (d3.event.sourceEvent.type != "wheel") yTransform.y = t.y;
// for a scroll, use the current y translate
else t.y = yTransform.y;
y2 = yTransform.rescaleY(y); // rescale y.
render();
})
The k and x values for yTranslate don't matter: the scale is always 1 as we aren't zooming in, and the x translate is irrelevant to rescale on the y axis. The above doesn't account for double click events, but I'll add that below.
var dots = d3.range(100)
.map(function() {
return {x: Math.random(), y: Math.random()}
})
var x = d3.scaleLinear().range([0,500])
var x2 = x.copy();
var y = d3.scaleLinear().range([0,300])
var y2 = y.copy();
var canvas = d3.select("canvas")
var context = canvas.node().getContext("2d");
// Just for reference:
var axis = d3.axisRight(y);
var g = d3.select("svg").append("g");
g.call(d3.axisRight(y2))
render();
var yTransform = d3.zoomIdentity;
var zoom = d3.zoom()
.on("zoom", function() {
var t = d3.event.transform;
x2 = t.rescaleX(x);
// For dbl clicks, d3.event.sourceEvent is null.
if (d3.event.sourceEvent && d3.event.sourceEvent.type != "wheel") yTransform.y = t.y;
else t.y = yTransform.y;
y2 = yTransform.rescaleY(y);
render();
})
canvas.call(zoom);
function render() {
context.clearRect(0,0,500,300);
dots.forEach(function(d) {
context.beginPath();
context.arc(x2(d.x), y2(d.y), 5, 0, 2 * Math.PI);
context.stroke();
})
g.call(d3.axisRight(y2));
}
canvas, svg {
position: absolute;
top: 0;
left: 0;
}
svg {
pointer-events:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<canvas width="500" height="300"></canvas>
<svg width="500" height="300"></svg>
As I'm modifying properties directly - which is not the most ideal.
Alternatively, we could track a translate offset on the y (the difference between a y translate with dbl clicks/wheel events and without those events). Both y offset and y translate could be used to create an appropriate zoom transform:
var yOffset = 0;
var lastY = 0;
var zoom = d3.zoom()
.on("zoom", function() {
var t = d3.event.transform;
x2 = t.rescaleX(x);
// For dbl clicks, d3.event.sourceEvent is null.
if (d3.event.sourceEvent && d3.event.sourceEvent.type != "wheel") {
lastY = t.y - yOffset;
y2 = d3.zoomIdentity.translate(0,t.y-yOffset).rescaleY(y);
}
else {
yOffset = t.y - lastY; // ignore change in y for dbl click and wheel events
}
render();
})
var dots = d3.range(100)
.map(function() {
return {x: Math.random(), y: Math.random()}
})
var x = d3.scaleLinear().range([0,500])
var x2 = x.copy();
var y = d3.scaleLinear().range([0,300])
var y2 = y.copy();
var canvas = d3.select("canvas")
var context = canvas.node().getContext("2d");
// Just for reference:
var axis = d3.axisRight(y);
var g = d3.select("svg").append("g");
g.call(d3.axisRight(y2))
render();
var yOffset = 0;
var lastY = 0;
var zoom = d3.zoom()
.on("zoom", function() {
var t = d3.event.transform;
x2 = t.rescaleX(x);
// For dbl clicks, d3.event.sourceEvent is null.
if (d3.event.sourceEvent && d3.event.sourceEvent.type != "wheel") {
lastY = t.y - yOffset;
y2 = d3.zoomIdentity.translate(0,t.y-yOffset).rescaleY(y);
}
else {
yOffset = t.y - lastY; // ignore change in y for dbl click and wheel events
}
render();
})
canvas.call(zoom);
function render() {
context.clearRect(0,0,500,300);
dots.forEach(function(d) {
context.beginPath();
context.arc(x2(d.x), y2(d.y), 5, 0, 2 * Math.PI);
context.stroke();
})
g.call(d3.axisRight(y2));
}
canvas, svg {
position: absolute;
top: 0;
left: 0;
}
svg {
pointer-events:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<canvas width="500" height="300"></canvas>
<svg width="500" height="300"></svg>
Related
I am struggling to make an image appear in a Canvas animated card. I can get text and drawn images to show up, but I can't seem to load the image and still have the ball follow the mouse. Why is that? I'm sure it's something super easy but I keep trying different things and am getting no where!
<script>
var canvas = document.querySelector("#myCanvas");
var context = canvas.getContext("2d");
var canvasPos = getPosition(canvas);
var mouseX = 525;
var mouseY = 325;
canvas.addEventListener("mousemove", setMousePosition, false);
function setMousePosition(e) {
mouseX = e.clientX - canvasPos.x;
mouseY = e.clientY - canvasPos.y;
}
function getPosition(el) {
var xPosition = 0;
var yPosition = 0;
while (el) {
xPosition += (el.offsetLeft - el.scrollLeft + el.clientLeft);
yPosition += (el.offsetTop - el.scrollTop + el.clientTop);
el = el.offsetParent;
}
return {
x: xPosition,
y: yPosition
};
}
function loadTeacher() {
var myImage = new Image();
myImage.src = 'images/teacher.jpg';
myImage.addEventListener("load", loadImage, false);
function loadImage(e) {
context.drawImage(myImage, 0, 75, 500, 350);
}
} loadTeacher();
function update() {
context.clearRect(0, 0, canvas.width, canvas.height);
//write text
context.font = "bold 12pt Helvetica, Ariel, sans-serif";
context.textAlign = "center";
context.fillStyle = "black";
context.fillText("This teacher needs an apple now! Drag the apple to her mouth.", 250, 50);
//draw circle
context.beginPath();
context.arc(mouseX, mouseY, 15, 0, 2 * Math.PI, true);
context.fillStyle = "red";
context.fill();
requestAnimationFrame(update);
}
update();
</script>
I have been experiencing bizarre behavior with the HTML5 Canvas in Chrome. As demonstrated in the example below, the images are not rendering correctly until the window is resized. All of the variables and properties have the exact same values both initially and on resize. Why does this happen?
Of course if the image hasn't loaded yet, the background won't display at all. You may need to refresh a few times.
<html>
<head>
</head>
<body>
<canvas id="test-canvas"></canvas>
</body>
<script>
var canvas = document.querySelector('#test-canvas');
var backgroundImage = new Image(100, 100);
backgroundImage.src = 'https://via.placeholder.com/100';
var dimensions = [];
var center = [];
var viewBox = [];
function paint() {
var ctx = canvas.getContext('2d');
dimensions = [canvas.width, canvas.height];
center = [dimensions[0] / 2, dimensions[1] / 2];
viewBox = [
-center[0], -center[1],
center[0], center[1],
];
ctx.translate(center[0], center[1]);
paintBackground(ctx);
}
function paintBackground(ctx) {
ctx.save();
var size = [100, 100]
var box = [
Math.floor(viewBox[0] / size[0]) * size[0],
Math.floor(viewBox[1] / size[1]) * size[1],
Math.ceil(viewBox[2] / size[0]) * size[0],
Math.ceil(viewBox[3] / size[1]) * size[1],
];
for (let x = box[0]; x < box[2]; x += size[0]) {
for (let y = box[1]; y < box[3]; y += size[1]) {
ctx.drawImage(backgroundImage, x, y, size[0], size[1]);
}
}
ctx.restore();
}
function resize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
paint();
}
window.addEventListener('resize', resize);
resize();
setTimeout(paint, 200);
</script>
</html>
The images should be covering the entire canvas...
But initially they only cover the lower right quadrant...
I figured it out. I was translating every time I painted. I realized I needed to put a call to save and restore within my paint method. This solved my problem.
function paint() {
var ctx = canvas.getContext('2d');
ctx.save() // <--- here!
dimensions = [canvas.width, canvas.height];
center = [dimensions[0] / 2, dimensions[1] / 2];
viewBox = [
-center[0], -center[1],
center[0], center[1],
];
ctx.translate(center[0], center[1]);
paintBackground(ctx);
ctx.restore() // <--- and here!
}
I need these images rendered in html5 canvas to be centered, rotated and resized depending on the size of the bounding box. I managed to rotate and resize the images but they are not centered anymore.
Can someone help me to fit these images in bounds and keep them in the center of the boxes? (fiddle updated)
http://jsfiddle.net/owtwv1a5/6/
var renderSprite = function(img, x, y, width,height, degree, scale){
var rads = degree * Math.PI/180;
var heightRatio = height/img.height;
var widthRatio = width/img.width;
var isRotated = (degree==90 || degree==270);
if (isRotated) {
var scale_ratio = height/img.width;
} else {
var scale_ratio = heightRatio;
}
var scaledImgHeight = img.height*scale_ratio;
var scaledImgWidth = img.width*scale_ratio;
var offsetX = width - scaledImgWidth;
if ((scaledImgHeight) < height) {
y += parseInt((height-scaledImgHeight)/2);
if (isRotated) {
x -= (scaledImgWidth - scaledImgHeight) / 2;
}
}
if ((scaledImgWidth) < width) {
x += parseInt((width-scaledImgWidth)/2);
if (isRotated) {
x -= (scaledImgWidth - scaledImgHeight) / 2;
}
}
ctx.save();
var centerX = x + scaledImgWidth * 0.5;
var centerY = y + scaledImgHeight * 0.5;
ctx.translate(centerX, centerY);
ctx.rotate(rads);
//ctx.scale(scale,scale);
ctx.translate(-centerX, -centerY);
ctx.drawImage(img, x,y, scaledImgWidth ,scaledImgHeight);
ctx.restore();
};
How do i bind onclick event to piechart segment?
https://github.com/sauminkirve/HTML5/blob/master/PieChart/piechart.html
A pie chart segment is really a wedge. You have several ways to hit-test a wedge.
One way is the math way:
Test if the mouse is within the radius of a circle created by the wedges.
If the radius test is true, then calculate the angle of the mouse versus the circle's centerpoint.
Compare that angle to each wedge. If the angle is between the starting and ending angle of a specific wedge's arc, then the mouse is inside that wedge.
Another way is to use canvas's built in path hit-testing method: isPointInPath
Redefine one wedge. There's no need to actually stroke or fill that wedge. Just do the commands from beginPath to closePath.
Use context.isPointInPath(mouseX,mouseY) to hit-test if the mouse is inside that wedge.
If isPointInPath returns true, you've discovered the wedge under the mouse. If not, then redefine & hit-test each of the other wedges.
Here's something I coded a while back that hit-tests the wedges of a pie chart when hovering and moves the wedge out of the pie when a wedge is clicked.
It uses the isPointInPath method to do the hit-testing:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.lineJoin = "round";
var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();
function Wedge(cx, cy, radius, startAngleDeg, endAngleDeg, fill, stroke, linewidth) {
this.cx = cx;
this.cy = cy;
this.radius = radius;
this.startAngle = startAngleDeg * Math.PI / 180;
this.endAngle = endAngleDeg * Math.PI / 180;
this.fill = fill;
this.stroke = stroke;
this.lineWidth = linewidth;
this.offsetX = 0;
this.offsetY = 0;
this.rr = radius * radius;
this.centerX = cx;
this.centerY = cy;
this.midAngle = this.startAngle + (this.endAngle - this.startAngle) / 2;
this.offsetDistance = 15;
this.explodeX = this.offsetDistance * Math.cos(this.midAngle);
this.explodeY = this.offsetDistance * Math.sin(this.midAngle);
this.isExploded = false;
};
Wedge.prototype.draw = function(fill, stroke) {
this.define();
this.fillStroke(fill, stroke);
ctx.beginPath();
ctx.arc(this.cx, this.cy, this.radius, 0, Math.PI * 2);
ctx.closePath();
ctx.lineWidth = 0.50;
ctx.stroke();
}
Wedge.prototype.fillStroke = function(fill, stroke) {
ctx.fillStyle = fill || this.fill;
ctx.fill();
ctx.strokeStyle = stroke, this.stroke;
ctx.lineWidth = this.lineWidth;
ctx.stroke();
}
Wedge.prototype.define = function() {
var x = this.cx + this.offsetX;
var y = this.cy + this.offsetY;
ctx.beginPath();
ctx.arc(x, y, this.radius, this.startAngle, this.endAngle);
ctx.lineTo(x, y);
ctx.closePath();
}
Wedge.prototype.ptAtAngle = function(radianAngle) {
var xx = (this.cx + this.offsetX) + this.radius * Math.cos(radianAngle);
var yy = (this.cy + this.offsetY) + this.radius * Math.sin(radianAngle);
return ({
x: x,
y: y
});
}
Wedge.prototype.explode = function(isExploded) {
this.isExploded = isExploded;
this.offsetX = isExploded ? this.explodeX : 0;
this.offsetY = isExploded ? this.explodeY : 0;
this.draw();
}
Wedge.prototype.isPointInside = function(x, y) {
var dx = x - (this.cx + this.offsetX);
var dy = y - (this.cy + this.offsetY);
if (dx * dx + dy * dy > this.rr) {
return (false);
}
var angle = (Math.atan2(dy, dx) + Math.PI * 2) % (Math.PI * 2);
return (angle >= this.startAngle && angle <= this.endAngle);
}
Wedge.prototype.marker = function(pos) {
ctx.beginPath();
ctx.arc(pos.x, pos.y, 3, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = "red";
ctx.fill();
}
function handleMouseDown(e) {
e.preventDefault();
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
clear();
for (var i = 0; i < wedges.length; i++) {
var wedge = wedges[i].wedge;
if (wedge.isPointInside(mouseX, mouseY)) {
wedge.explode(!wedge.isExploded);
}
wedge.draw();
}
}
function handleMouseUp(e) {
e.preventDefault();
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// Put your mouseup stuff here
isDown = false;
}
function handleMouseOut(e) {
e.preventDefault();
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// Put your mouseOut stuff here
isDown = false;
}
function handleMouseMove(e) {
e.preventDefault();
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
for (var i = 0; i < wedges.length; i++) {
var wedge = wedges[i].wedge;
if (wedge.isPointInside(mouseX, mouseY)) {
wedge.draw("black");
} else {
wedge.draw();
}
}
}
$("#canvas").mousedown(function(e) {
handleMouseDown(e);
});
$("#canvas").mousemove(function(e) {
handleMouseMove(e);
});
$("#canvas").mouseup(function(e) {
handleMouseUp(e);
});
$("#canvas").mouseout(function(e) {
handleMouseOut(e);
});
function clear() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
var PI2 = Math.PI * 2;
var cx = 150;
var cy = 150;
var r = 100;
var line = 2;
var stroke = "black";
var wedges = [];
wedges.push({
percent: 18,
fill: "red"
});
wedges.push({
percent: 30,
fill: "blue"
});
wedges.push({
percent: 25,
fill: "green"
});
wedges.push({
percent: 13,
fill: "purple"
});
wedges.push({
percent: 14,
fill: "gold"
});
var rAngle = 0;
for (var i = 0; i < wedges.length; i++) {
var wedge = wedges[i];
var angle = 360 * wedge.percent / 100;
wedge.wedge = new Wedge(cx, cy, r, rAngle, rAngle + angle, wedge.fill, "black", 1);
wedge.wedge.draw();
rAngle += angle;
}
window.onscroll = function(e) {
var BB = canvas.getBoundingClientRect();
offsetX = BB.left;
offsetY = BB.top;
}
body {
background-color: ivory;
}
#canvas {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Hover wedge to highlight it<br>Click wedge to explode that wedge</h4>
<canvas id="canvas" width=300 height=300></canvas>
How to slide mouse in circular ?
Draw an arc and a mouse pointer in a canvas. Mouse should be drag gable on the circular path?
//function to create mouse event to drag the mouse hover the arc
function mousedrag() {
var canvasoffset = $(this.canvas).offset();
var offsetX = canvasoffset.left;
var offsetY = canvasoffset.top;
var mouseX = parseInt(e.offsetX || e.clientX - offsetX);
var mouseY = parseInt(e.offsetY || e.clientY - offsetY);
var radius = this.width / 2;
var twoPI = 2 * Math.PI;
var toRad = twoPI / 360;
var r_width = this.width * 0.8;
var radial_Angle = Math.atan2(mouseY - radius,mouseX - radius);
var p_side_x = radius + r_width * Math.cos(radial_Angle);
var p_side_y = radius + r_width * Math.sin(radial_Angle);
var p_mouse_x = radius + ((r_width+10) * Math.sin(radial_Angle));
var p_mouse_y = radius + ((r_width+ 10) * Math.sin(radial_Angle));
var imgData = this.ctx.getImageData(p_side_x, p_side_y, 1, 1).data;
var selectedColor = new Color(imgData[0], imgData[1], imgData[2]);
clearDraw();
renderSpectrum();
renderMouse(p_side_x, p_side_y, p_mouse_x, p_mouse_y);
}
mouse handle does not slide properly.
You can't actually force the mouse to be constrained into a circle.
But you can calculate the mouse position relative to a centerpoint.
// define a centerpoint
var cx=150;
var cy=150;
var angleVersusCenter=0;
// listen for mouse moves
function handleMouseMove(e){
// get the mouse position
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// set the current radian angle of the mouse
// versus the centerpoint
var angleVersusCenter = Math.atan2( mouseY-cy, mouseX-cx );
}
A Demo: http://jsfiddle.net/m1erickson/z6cQB/
Here is the jQuery roundSlider plugin for your requirement, check here http://roundsliderui.com/. This might helps you.
This roundslider having the similar options like the jQuery ui slider. It support default, min-range and range slider type. Not only the round slider it also supports various circle shapes such as quarter, half and pie circle shapes.
For more details check the demos and documentation page.
Please check the demo from jsFiddle.
Live demo:
$("#slider").roundSlider({
width: 10,
handleSize: "+8",
value: "40"
});
$("#half-slider").roundSlider({
width: 10,
circleShape: "half-top",
handleSize: "+8",
value: "80"
});
.rs-control {
display: inline-block;
float: left;
margin-left: 30px;
}
.rs-control .rs-path-color {
background-color: #e9e9e9;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.roundslider/1.0/roundslider.min.js"></script>
<link href="https://cdn.jsdelivr.net/jquery.roundslider/1.0/roundslider.min.css" rel="stylesheet"/>
<div id="slider" class="rslider"></div>
<div id="half-slider" class="rslider"></div>
Screenshots with different appearances:
Check more details about different theme from here.