Published
Edited
Apr 3, 2022
Insert cell
# FootBallRules-d3.js
Insert cell
d3s = require("d3-soccer")
Insert cell
height = 340
Insert cell
md`## オフサイド`
Insert cell
{
const pitch = d3s.pitch().height(height);
const sx = d3.scaleLinear().domain([0, 105]).range([0, pitch.width()]);
const sy = d3.scaleLinear().domain([0, 68]).range([0, pitch.height()]);
d3.select("#chart").selectAll("svg").remove();
d3.select("#chart").selectAll("g").remove();
const svg = d3
.select("#chart")
.append("svg")
.attr("width", pitch.width())
.attr("height", pitch.height());
const g = svg.append("g");
g.call(pitch);

const players = [
{ color: "#f55", x: 30, y: 10 },
{ color: "#def", x: 3, y: 24 },
{ color: "#def", x: 6, y: 34 }
];
const g2 = g.append("g").attr("class", "players");

g2.selectAll("circle")
.data(players)
.join("circle")
.attr("r", 8)
.attr("cx", (d) => sx(d.x))
.attr("cy", (d) => sy(d.y))
.attr("stroke", "#888")
.attr("fill", (d) => d.color)
.call(
d3
.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended)
);

svg.call(
d3
.zoom()
.extent([
[0, 0],
[width, height]
])
.scaleExtent([1, 8])
.on("zoom", zoomed)
);
function zoomed({ transform }) {
g.attr("transform", transform);
}
function dragstarted() {
d3.select(this).raise();
g.attr("cursor", "grabbing");
}

function dragged(event, d) {
d3.select(this)
.attr("cx", (d.x = event.x))
.attr("cy", (d.y = event.y));
update();
}

function dragended() {
g.attr("cursor", "grab");
}

function update() {
// オフサイド判定
let minX = 52.5;
d3.select(".players")
.selectAll("circle")
.each((d) => {
if (minX > d.x) {
console.log(d);
minX = Math.min(d.x, 52.5);
console.log(minX);
}
});
d3.select(".offside-line").remove();
svg
.append("g")
.append("line")
.attr("class", "offside-line")
.data([{ y1: sy(0), y2: sy(68), x: sx(minX) }])
.join("line")
.attr("x1", (d) => d.x)
.attr("y1", (d) => d.y1)
.attr("x2", (d) => d.x)
.attr("y2", (d) => d.y2)
.attr("stroke", "blue");
}
}
Insert cell
<div id="chart"></div>
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more