Reputation: 1611
Hi I am trying to do zoom and pan on some images. I've got the example from this link: http://bl.ocks.org/mbostock/3681006 the main difference there is that they drawing shapes not images. Here is a the script, what I've done
https://jsfiddle.net/t1gqg1m6/1/
var width = 960,
height = 500;
var randomX = d3.random.normal(width / 2, 80),
randomY = d3.random.normal(height / 2, 80);
var data = d3.range(2000).map(function() {
return [
randomX(),
randomY()
];
});
var x = d3.scale.linear()
.domain([0, width])
.range([0, width]);
var y = d3.scale.linear()
.domain([0, height])
.range([height, 0]);
var canvas = d3.select("canvas")
.attr("width", width)
.attr("height", height)
.call(d3.behavior.zoom().x(x).y(y).scaleExtent([1, 8]).on("zoom", zoom))
.node().getContext("2d");
function zoom() {
canvas.clearRect(0, 0, width, height);
draw();
}
var img = new Image();
img.onload = function () {
function draw(){
for(var i=0;i<=500;i+=50){
canvas.drawImage(img, i, 10, 50, 40);
}
}
draw();
}
img.src = "http://static.dnaindia.com/sites/default/files/styles/half/public/2016/04/02/444652-google-photos-emoji-google-image-search-using-emoji-coolkengzz-shutterstock.jpg?itok=b1lBccFF";
if some one can help would be great. Thank you in advance.
Upvotes: 1
Views: 2680
Reputation: 32327
Make your draw function global, so that it can be called from zoom function and also from the image onload function.
function draw() {
for (var i = 0; i <= 500; i += 50) {
canvas.drawImage(img, x(i), 10, 50, 40);
}
}
Next instead of:
canvas.drawImage(img, i, 10, 50, 40);
it should have been:
canvas.drawImage(img, x(i), 10, 50, 40);
so that the zoom/pan calculates the new position correctly.
working code here
Upvotes: 1