Save only a certain part of an HTML canvas

后端 未结 2 1390
一个人的身影
一个人的身影 2021-01-05 17:10

Is it possible to save or export only a certain part of the canvas rather than the whole canvas?

http://i.stack.imgur.com/hmvYh.jpg

At the moment, when I sav

2条回答
  •  耶瑟儿~
    2021-01-05 17:36

    Yes you can. Here is the JSFiddle.

    First, you need to take a clipping of the image in your canvas. This is pretty simple. I made another canvas (a hidden one) and used the context.drawImage

    var hidden_ctx = hidden_canvas.getContext('2d');
    
    hidden_ctx.drawImage(
        MainCanvas,
        startClippingX,
        startClippingY,
        clippingWidth,
        clippingHeight,
        pasteX,
        pasteY,
        pasteWidth,
        pasteHeight
    );
    

    Now, we need the Data URL from this canvas so we can download the contents. For this, we will use the canvas.toDataURL method.

    var data_url = hidden_canv.toDataURL("image/png");
    

    Now, all we need to do is make a download link (an a element with an href attribute of our data_url) and we're done!

提交回复
热议问题