简体   繁体   English

无法使用现有图像清除画布

[英]cannot clear canvas with existing image

I am trying to blank canvas when there is image already in it. 我正在尝试在画布中已有图像时将其空白。

I want to remove old image and load new image that I am getting from var getfrontimage . 我想删除旧图像并加载从var getfrontimage获取的新图像。

But It failed me. 但这使我失败了。

    $('#fittocanvasfront').click(function () {
        var canvas = document.getElementById("canvas-front");
        var c = canvas.getContext("2d");
        var getfrontimage = $('#image-tocanvaschangefront').attr('src');

        var img = new resize(getfrontimage);
        function resize(src) {
            console.log('blank canvas');
            canvas.width = canvas.width;
            var image = new Image();
            image.src = getfrontimage;
            image.width = canvas.width;
            image.height = canvas.height;
            image.onload = function () {
                // clearing canvas
                c.clearRect(0, 0, canvas.width, canvas.height);
                //loading image
                c.drawImage(image, 0, 0);
                //creating a hole in canvas
                var centerX = canvas.width / 2;
                var centerY = canvas.offsetTop;
                var radius = 30;
                c.beginPath();
                c.arc(centerX, centerY, radius, 0, 2 * Math.PI, true);
                c.fillStyle = 'black';
                c.fill();
            }
        }
    });

Into the script- 进入脚本-

I have image in <img> tag- 我在<img>标签中有图片-

   var getfrontimage = $('#image-tocanvaschangefront').attr('src');

this above image is what i will be using after clearing canvas. 上面这张图片是清除画布后我将要使用的图片。

So I tried doing canvas empty as below when image is being loaded- 所以我尝试在加载图像时按以下方式将画布清空-

 c.clearRect(0, 0, canvas.width, canvas.height);

But this didn't work, I tried doing canvas empty on click- 但这没有用,我尝试在点击时将画布清空

   $('#fittocanvasfront').click(function () {
            var canvas = document.getElementById("canvas-front");
            var c = canvas.getContext("2d");
            c.clearRect(0, 0, canvas.width, canvas.height);
              });

How do I empty this canvas with existing image in it. 如何清空包含现有图像的画布。

What you are saying is not true. 你说的不是真的。 You can clear of any image using clearRect . 您可以使用clearRect清除任何图像。 Please see fiddle with your code where image's cleared on click. 请查看您的代码,在单击时清除图像的小提琴

$("#canvas-front").click(function(){
   c.clearRect(0, 0, canvas.width, canvas.height);
});

Hard to say what you're doing wrong, since you didn't provide the full code, use the code I provided in fiddle and all should be fine. 很难说您在做什么错,因为您没有提供完整的代码,请使用我在提琴中提供的代码,一切都很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM