简体   繁体   中英

Why does the previous image draw on my HTML5 canvas?

this code draws an image of the user's local computer on a canvas then slide it on some other canvases for slide puzzle game

function drawImage(event) {

        if (event.target.files.length <= 0) return;
        var files = event.target.files;
        var URL = window.URL || window.webkitURL;
        var img = $("#image")[0];

        img.src = URL.createObjectURL(files[0]);

        getCanvas("karajan").drawImage(img, 0, 0, img.width, img.height, 0, 0, 450, 450);

       ...........

    }

    function getCanvas(id) {
        var canvas = $("#" + id)[0];
        if (canvas.getContext) {
            return canvas.getContext("2d");
        }
        return undefined;
    }

and a tag that inputs image file from local computer

<input type="file" accept="image/*" id="image_input" onchange="drawImage(event)"/>
<img id="image"/>

and when user want to change the image, the canvas will draw with previous image. I don't know why. in the first lines of drawImage function image changes with newer image and draws on canvas

The canvas does not clear itself, you have to tell it to clear. You can either wipe the whole thing with, or a controlled area, using clearRect(x,y,w,h) . After this, you can draw the new image.

I assume the image is not actually "loaded" until the current script terminates. That means you should listen to the load event of the image and only then draw it to the canvas.

I did some restructuring of your code as well. If you already have jQuery available, use it:

$(function() {
    var URL = window.URL || window.webkitURL;
    var $image = $('#image').on('load', function() {
        // clear canvas here
        getCanvas("karajan")
            .drawImage(this, 0, 0, this.width, this.height, 0, 0, 450, 450);
        // ...
    });

    $('#image_input').on('change', function() {
        if (this.files.length === 0) return;

        $image.prop('src', URL.createObjectURL(this.files[0]));
    });
});

You should still clear the canvas though, as Kolink suggested. Otherwise, if a new, smaller image is loaded, parts of the previous, larger image will still be visible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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