Skip to content

Instantly share code, notes, and snippets.

@takurx
Forked from ganezasan/.gitignore
Created April 14, 2016 07:40
Show Gist options
  • Save takurx/ebda798d84a02731b682f731db1b8fb9 to your computer and use it in GitHub Desktop.
Save takurx/ebda798d84a02731b682f731db1b8fb9 to your computer and use it in GitHub Desktop.
d3 Animation Image

d3.jsを使用したアニメーション

  • ドッラグ&ドロップ
  • 回転
  • 拡大
  • 縮小
  • イメージの追加
<!DOCTYPE html>
<meta charset="utf-8">
<style>
* {
margin: 0;
padding: 0;
border: 0;
}
body {
background: #fff;
}
</style>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<button type="button" class="btn btn-primary" id="addImage">追加</button>
<button type="button" class="btn btn-success" id="wheel">回転</button>
<button type="button" class="btn btn-info" id="big">拡大</button>
<button type="button" class="btn btn-warning" id="small">縮小</button>
<div id="svg_area">
<svg id="animation" width="1000" height="1000"></svg>
</div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var imageAnimation = new function(){
// 複数画像対応.
var instances = {};
this.init = function(id,baseId){ instances[id] = new ImageAnimation(baseId); };
function ImageAnimation(id){
var drag,dgrop;
//ドラッグ時のイベントをセット
drag = d3.behavior.drag()
.on("drag", function(d,i) {
d.x += d3.event.dx;
d.y += d3.event.dy;
d3.select(this).attr("transform", function(d,i){
return "translate(" + [ d.x,d.y ] + "),rotate("+d.r+",160, 160),scale("+d.scale+","+d.scale+")";
})
});
dgrop = d3.select(id).append("g")
.data([ {"x":20, "y":20, "r":1 , "scale":1} ])
.attr("x",0)
.attr("y",0)
.attr("transform","translate(0,0)")
.append('image')
.attr("x",0)
.attr("y",0)
.attr("width",300)
.attr("height",300)
.attr("xlink:href","octocat.png")
.call(drag);
//回転
$("#wheel").bind("click",function(){
dgrop.attr("transform", function(d,i){
d.r=d.r-30;
return "translate(" + [ d.x,d.y ] + "),rotate("+d.r+" ,160, 160),scale("+d.scale+","+d.scale+")";
});
});
//拡大
$("#big").bind("click",function(){
dgrop.attr("transform", function(d,i){
d.scale=d.scale*1.2;
return "translate(" + [ d.x,d.y ] + "),rotate("+d.r+" 160 160),scale("+d.scale+","+d.scale+")";
});
});
//縮小
$("#small").bind("click",function(){
dgrop.attr("transform", function(d,i){
d.scale=d.scale*0.8;
return "translate(" + [ d.x,d.y ] + "),rotate("+d.r+" 160 160),scale("+d.scale+","+d.scale+")";
});
});
}
}
//追加
imageAnimation.init(0,"#animation");
var imagenum = 1;
$("#addImage").bind("click",function(d){
imageAnimation.init(imagenum,"#animation");
imagenum++;
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment