Codemole
Codemole

Reputation: 3189

Any possible way to draw Any part of web page into the Canvas

everyone.

I know how to copy an image from the HTML Image Element into Canvas using follow code snap:

ctx = canvas.getContext("2d");
ctx.drawImage(imgElement, 0, 0, 300, 300);

But what I wanna do is, to drawImage of any part of the page. So the page might contain ImageElement, some Borders with various colors, Overlaid layers with different background image, some text with custom google fonts, etc. So I just wanna copy any part of the page into the canvas, as if screen capture tool does.

Is this possible with javascript? Or theoretically impossible yet? Any plan for browser producers to support this kind of function?

Upvotes: 0

Views: 230

Answers (1)

DavidDomain
DavidDomain

Reputation: 15293

You could use html2canvas to take "screenshots" of your webpage or parts of it.

Here is an example:

var btn = document.getElementsByTagName('button')[0];
var h1 = document.getElementsByTagName('h1')[0];
var h1Rect = h1.getBoundingClientRect();

btn.addEventListener('click', function() {
  html2canvas(document.body, {
    width: h1Rect.width,
    height: h1Rect.height + h1Rect.top,
    onrendered: function(canvas) {
      document.body.appendChild(canvas);
    }
  });
});
span {
  color: red;
  font-weight: normal;
  font-style: italic;
}

canvas {
  margin-top: 6px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<h1><span>Hello</span> HTML2Canvas</h1>
<button>Click to draw h1 to canvas</button>

Upvotes: 2

Related Questions