Crop an image displayed in a Canvas

后端 未结 4 1592
太阳男子
太阳男子 2020-12-15 13:08

I have a canvas tag:


I want to add a crop functionality, so I

4条回答
  •  误落风尘
    2020-12-15 13:49

    Use the method getImageData with the selected rectangle coordinates. For example:

    let imageData = ctx.getImageData(65, 60, 100, 100);
    

    Then create a secondary canvas with the desired sizes and use putImageData to set the pixels:

    let canvas1 = document.createElement("canvas");
    canvas1.width = 100;
    canvas1.height = 100;
    let ctx1 = canvas1.getContext("2d");
    ctx1.rect(0, 0, 100, 100);
    ctx1.fillStyle = 'white';
    ctx1.fill();
    ctx1.putImageData(imageData, 0, 0);
    

    Finally use toDataURL to update the image:

    dstImg.src = canvas1.toDataURL("image/png");
    

    See the full sample I've prepared for you in CodePen

提交回复
热议问题