Home  >  Article  >  Web Front-end  >  Introduction to html screenshots based on canvas

Introduction to html screenshots based on canvas

不言
不言Original
2018-07-03 09:24:032469browse

This article mainly introduces a small screenshot demo implemented in HTML based on canvas, which has certain reference value. If you are interested, you can learn more

Write it first

I remember seeing a share on Renren before, explaining the screenshot solution based on js. I don’t remember the details. I just remember that it was quite interesting and seemed to use canvas? So this time I plan to write one myself to share with everyone the author’s ideas. This is just a very simple small demo. If there are any bugs, please submit issues. As usual, po code address.

Rendering

Overall idea

  • Set start/end shortcut keys

  • After starting, draw the DOM into canvas to cover the original DOM interface

  • Add a canvas simulation mouse screenshot area

  • Add A canvas is used to draw the browser interface corresponding to the mouse screenshot area (captured from the first canvas)

  • Save the captured image

1. Set the start/end shortcut keys

Due to the conflicts that shortcut keys may cause, we hope that the start shortcut key can not limit the number of shortcut keys, so an array is used in the first parameter transmitted in the form.

function screenShot(quickStartKey, EndKey) {
  //兼容性考虑不使用...扩展字符串
  var keyLength = quickStartKey.length
  var isKeyTrigger = {}
  var cantStartShot = false
  ...
  quickStartKey.forEach(function(item) { //遍历参数数组
    isKeyTrigger[item] = false //默认数组中所有键都没有触发
  })
  $('html').on('keyup', function(e) {
    var keyCode = e.which
    if(keyCode === EndKey) {
      ...
    } else if(!cantStartShot) {
      isKeyTrigger[keyCode] = true
      var notTrigger = Object.keys(isKeyTrigger).filter(function(item) {
        return isKeyTrigger[item] === false //查看有没有需要触发的快捷键
      })
      if(notTrigger.length === 0) { //没有需要触发的快捷键即可以开始截图
        cantStartShot = true
        beginShot(cantStartShot)
      }
    }
  })

2. Draw the DOM into canvas to cover the original DOM interface

If you use the native method, you can refer to the introduction of drawing DOM in canvas under MDN. The trickiest part is that you need to create an SVG image containing XML involving the element . How to calculate the DOM currently displayed by the browser and extract it is actually the most cumbersome. Okay, actually the author doesn't have a good idea to manually implement an =. =, so I chose this html2canvas library to accomplish this. The general calling method is as follows:

function beginShot(cantStartShot) {
    if(cantStartShot) {
        html2canvas(document.body, {
            onrendered: function(canvas) {
                //得到与界面一致的canvas图像
            }
        })
    }
}

3. Add a canvas simulation mouse screenshot area

The implementation of this place was originally intended to use the native canvasAPI, but there is a problem involved. That is, after the mouse is pressed and started dragging, the canvas needs to be drawn in real time, which leads to a concept similar to PS layers. Every time mousemove is used, a current screenshot frame is drawn, but when mousemove is triggered next time Just delete the previous screenshot box. This is used to simulate the real-time drawing process. Unfortunately, the author has not found a way to use the canvas native API. If there is, please tell me how to mark the drawn pictures. Here the author uses a Jq-based canvas library called Jcanvas, which gives the concept of layers, that is, only one picture can be drawn on a layer, and the layer can be marked with a name. This meets the author's needs and is implemented as follows:

$('#' + canvasId).mousedown(function(e) {
    $("#"+canvasId).removeLayer(layerName) //删除上一图层
    layerName += 1
    startX = that._calculateXY(e).x //计算鼠标位置
    startY = that._calculateXY(e).y
    isShot = true
    $("#"+canvasId).addLayer({
        type: 'rectangle', //矩形
        ...
        name:layerName, //图层名称
        x: startX,
        y: startY,
        width: 1,
        height: 1
    })
}).mousemove(function(e) {
    if(isShot) {
        $("#"+canvasId).removeLayer(layerName)
        var moveX = that._calculateXY(e).x
        var moveY = that._calculateXY(e).y
        var width = moveX - startX
        var height = moveY - startY
        $("#"+canvasId).addLayer({
            type: 'rectangle',
            ...
            name:layerName,
            fromCenter: false,
            x: startX,
            y: startY,
            width: width,
            height: height
        })
        $("#"+canvasId).drawLayers(); //绘制
    }
    })

4. Add a canvas to draw the browser interface corresponding to the mouse screenshot area

var canvasResult = document.getElementById('canvasResult')
              var ctx = canvasResult.getContext("2d");
              ctx.drawImage(copyDomCanvas, moveX - startX > 0 ? startX : moveX, moveY - startY > 0 ? startY : moveY, width, height, 0, 0, width, height )
              var dataURL = canvasResult.toDataURL("image/png");

pass drawImage intercepts the image, and then uses the toDataURL method to convert the image to base64 encoding

5. Save the intercepted image

function downloadFile(el, fileName, href){
      el.attr({
        'download':fileName,
        'href': href
      })
  }
  ...
downloadFile($('.ok'), 'screenShot' + Math.random().toString().split('.')[1] || Math.random()  + '.png', dataURL)
// 传入按键对象、图像保存随机名、base64编码的图像

The download attribute of the a tag is used. When Users can download directly after clicking.

Deployment

##Dependencies

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/jcanvas/16.7.3/jcanvas.min.js"></script>
<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.min.js"></script>

Configuration shortcut keys

screenShot([16, 65], 27) // 开始快捷键设置为shift+a;退出键为ESC

Finally

The most disgusting parts of the article (DOM writing to canvas, canvas setting layer) are implemented using two libraries respectively. The author will also pay attention to how to use the native API in the future. To implement these operations, although I personally think it's a bit difficult to write it yourself. .

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

canvas simulates the code for electronic lottery scratch-offs

Method of using HTML5 Canvas to draw shadow effects

The above is the detailed content of Introduction to html screenshots based on canvas. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn