Skip to content

Instantly share code, notes, and snippets.

@pbogden
Last active November 30, 2016 14:43
Show Gist options
  • Save pbogden/f1dab813887832c28374 to your computer and use it in GitHub Desktop.
Save pbogden/f1dab813887832c28374 to your computer and use it in GitHub Desktop.
canvas svg

###Overlay SVG on canvas

  • Use a positioned container (#myContainer is position: relative) for the overlay
  • Overlay the canvas and svg elements using position: absolute
  • A CSS border on the canvas element displaces the canvas relative to the SVG
  • d3.selection.insert can help when ordering SVG and canvas elements
  • Uses globalAlpha and d3.timer to gradually fade in the canvas element
<!DOCTYPE html>
<meta charset="utf-8"/>
<title>canvas-svg</title>
<style>
body {
margin: 0;
}
#myContainer {
position: relative;
}
#myCanvas1, #myCanvas2, #mySvg {
position: absolute;
top: 0;
left: 0;
}
</style>
<body>
<div id="myContainer">
<div id="mySvg"></div>
<div id="myCanvas1"></div>
<div id="myCanvas2"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>
var borderWidth = 10,
width = 960;
height = 500;
var ctx1 = d3.select('#myCanvas1').append("canvas").node().getContext('2d'),
ctx2 = d3.select('#myCanvas2').append("canvas").node().getContext('2d'),
img = new Image();
d3.select('#myContainer').insert("svg", "#myCanvas1")
.attr('width',width)
.attr('height',height)
.style('background','#aaa')
.append('rect')
.attr('width', 40)
.attr('height', 40)
.style('fill', 'black');
d3.select('#myCanvas1 canvas')
.attr('width', width - 2*borderWidth)
.attr('height', height - 2*borderWidth)
.style('border', borderWidth + "px solid rgba(255, 0, 0, .5");
img.src = 'pooch.png';
img.onload = function() {
ctx1.globalAlpha = 0.0;
ctx1.drawImage(img, 0, 0);
var n = 0, m = 1000;
d3.timer(function () {
++n;
ctx1.globalAlpha = n/m; // the way to fade-in an entire image
ctx1.drawImage(img, 0, 0);
ctx2.fillStyle = "rgb(255,0,0)";
ctx2.fillRect(10, 10, 55, 50);
ctx2.fillStyle = "rgba(0, 0, 255, 0.4)";
ctx2.fillRect (30, 30, 55, 50);
if (n >= m) return true;
}, 1000);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment