D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
1Cr18Ni9
Full window
Github gist
canvas globalCompositeOperation
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"></script> <style> * { box-sizing: border-box; } #app { display: flex; flex-wrap: wrap; } .box { border: 1px solid gray; width: 120px; } .box__body canvas { display: block; margin: auto; } .box__title { text-align: center; } </style> </head> <body> <div id="app"></div> <script> var types = [ "source-over", "source-in", "source-out", "source-atop", "destination-over", "destination-in", "destination-out", "destination-atop", "lighter", "copy", "xor", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity" ]; var w = 100, h = 100, velocity = 2; var circles = types.map(function (t) { var rad = Math.floor(Math.random() * 30 + 30) * Math.PI / 180; return { r: 10, x: Math.floor(Math.random() * (w - 10) + 10), y: Math.floor(Math.random() * (h - 10) + 10), dx: Math.sin(rad) * velocity, dy: Math.cos(rad) * velocity, alpha: t }; }); var evt = function (d) { var p = d3.mouse(this); d.x = p[0]; d.y = p[1]; }; d3.select("#app") .selectAll(".box") .data(circles) .enter() .append("div") .attr("class", "box") .each(function (d) { var parent = d3.select(this); parent.append("div") .attr("class", "box__body") .append("canvas") .on("mouseenter", function () { d.fixed = true; }) .on("mousemove", evt) .on("mouseleave", function () { d.fixed = false; }) .attr("width", w) .attr("height", h); parent.append("div") .attr("class", "box__title") .text(d.alpha); }); var canvas = d3.selectAll("canvas"); function drawBg (ctx) { ctx.shadowOffsetX = 0; ctx.shadowOffsetY = 0; ctx.shadowBlur = 20; ctx.shadowColor = "red"; ctx.fillStyle = "red"; ctx.beginPath(); ctx.arc(50, 30, 20, 0, Math.PI * 2, false); ctx.fill(); ctx.shadowColor = "blue"; ctx.fillStyle = "blue"; ctx.beginPath(); ctx.arc(30, 70, 20, 0, Math.PI * 2, false); ctx.fill(); ctx.shadowColor = "green"; ctx.fillStyle = "green"; ctx.beginPath(); ctx.arc(70, 70, 20, 0, Math.PI * 2, false); ctx.fill(); } function redraw () { canvas.each(function (d) { var ctx = this.getContext("2d"); ctx.save(); ctx.clearRect(0, 0, w, h); drawBg(ctx); ctx.fillStyle = "yellow"; ctx.globalCompositeOperation = d.alpha; ctx.beginPath(); ctx.arc(d.x, d.y, d.r, 0, Math.PI * 2, false); ctx.fill(); if (!d.fixed) { d.x += d.dx; d.y += d.dy; if (d.x < 0 || d.x > (w - d.r)) { d.dx *= -1; } if (d.y < 0 || d.y > (h - d.r)) { d.dy *= -1; } } ctx.restore(); }); window.requestAnimationFrame(redraw); } redraw(); </script> </body>
https://d3js.org/d3.v4.min.js